4

今天我们学习了 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 绑定到另一个函数。任何帮助表示赞赏!

4

3 回答 3

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

执行此操作的惯用方法(在 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)
于 2012-04-19T06:27:18.453 回答
4

等效的 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 的代码更漂亮一点!)

于 2012-04-19T06:28:36.677 回答
1

还有另一种方法可以在不使用引用的情况下获得相同的东西:

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;;

Note that this code involves unguarded recursive types: the type of a helper is ('a -> int -> bool) -> int -> bool as 'a, meaning that the first argument to a helper is a function whose first argument is a helper. Such types are accepted by Ocaml, but only if you pass the -rectypes option to the compiler.

Using more functions you can do away with the rec altogether. This is not a direct answer to your question, but rather a side-track showing how that pattern would look in a purely functional way.

于 2012-04-19T07:56:01.650 回答