还有另一种方法可以在不使用引用的情况下获得相同的东西:
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.