OCamlでTCO

末端再帰最適化。

次のコードをCompiler Explorerで見ると、dupのcall/retが、dup_tailでは、TCOでjeに置き換えられている。

let rec dup = function
	| [] -> []
	| h :: t -> h :: h :: dup t ;;

let dup_tail lst =
	let rec aux acc = function
	| [] -> acc
	| h :: t -> aux (h :: h :: acc) t in
	List.rev (aux [] lst);;

let main = dup [1;2;3];;

3.1.1.5. Tail Recursion · Functional Programming in OCaml

A function is tail recursive if it calls itself recursively but does not perform any computation after the recursive call returns, and immediately returns to its caller the value of its recursive call.

OCamlとアセンブリ言語から読み解く末尾再帰最適化

Backlinks

There are no notes linking to this note.