Function OCaml中的递归函数引用?

Function OCaml中的递归函数引用?,function,reference,ocaml,sml,Function,Reference,Ocaml,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; 我正在使用ocaml,它非常相似,但我在做同样的事情时遇到了麻烦。我发现最接近的是 let tempFunc {content

今天我们学习了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;
我正在使用ocaml,它非常相似,但我在做同样的事情时遇到了麻烦。我发现最接近的是

let tempFunc {contents =x}=x;;

但我真的不明白这一点,以及如何将tempFunc与另一个函数联系起来。感谢您的帮助

您的代码在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
实现这一点的惯用方法(在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)

等效的OCaml代码是

let tempFunc = ref (fun (k: int) -> 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);;

tempFunc := odd;;
正如您所说,它实际上与SML代码相同


(编辑添加:事实上,Thomas的代码有点漂亮!)

还有另一种方法可以在不使用引用的情况下实现同样的功能:

let rec even_helper f x = if x = 0 then true else f even_helper (x-1);;
let rec odd_helper f x = if x = 0 then false else f odd_helper (x-1);;
let even = even_helper odd_helper;;
let odd = odd_helper even_helper;;
请注意,此代码涉及无保护的递归类型:辅助对象的类型是
('a->int->bool)->int->bool as'a
,这意味着辅助对象的第一个参数是其第一个参数为辅助对象的函数。Ocaml接受这样的类型,但前提是将
-rectypes
选项传递给编译器


使用更多功能,您可以完全取消
rec
。这不是对你问题的直接回答,而是一个旁白,显示了该模式在纯功能性方面的外观。

(使用
在SML中也是惯用的。这只是一个例子,展示了结婚的想法。)哇,我觉得我以前尝试过,但出现了错误,但我肯定错过了什么,非常感谢@JeffreyScofield是的,是的,但是你需要
-矩形字体
@gilles:我知道我遗漏了什么。。。稍后,我将使用递归类型的一种常见解决方法对其进行编辑。。。