OCaml中的递归函数引用?

joe*_*bro 4 ocaml reference function sml

今天我们在SML中学到了"打结",你有类似的东西

val tempFunc = ref (fn k:int => true);
fun even x = if x = 0 then true else !tempFunc(x-1);
fun odd x = if x = 0 then false else even(x-1);
tempFunc := odd;
Run Code Online (Sandbox Code Playgroud)

而我正在使用类似的ocaml,但我只是在做同样的事情.我发现的最接近的是

let tempFunc {contents =x}=x;;
Run Code Online (Sandbox Code Playgroud)

但我真的不明白,以及如何将tempFunc绑定到另一个函数.任何帮助表示赞赏!

Tho*_*mas 9

您在OCaml中直接翻译的代码是:

let tempFunc = ref (fun k -> true)
let even x = if x = 0 then true else !tempFunc (x-1)
let odd x = if x = 0 then false else even (x-1)
let () = tempFunc := odd
Run Code Online (Sandbox Code Playgroud)

这样做的惯用方法(就像在SML中一样)是使用递归函数:

let rec even x = if x = 0 then true  else odd  (x-1)
and     odd  x = if x = 0 then false else even (x-1)
Run Code Online (Sandbox Code Playgroud)