I'm trying to understand the Y combinator in OCaml. I took some code from here , and I'm trying to use it to write the Ackermann function. In the examples in the link, the functions only require one argument. The Ackermann function requires two arguments, and I keep having syntax errors because of it. The code I have so far is
type 'a mu = Roll of ('a mu -> 'a);;
let unroll (Roll x) = x;;
let fix f = (fun x a -> f (unroll x x) a) (Roll (fun x a -> f (unroll x x) a));;
let acker f = function
0, n -> n + 1
| m, 0 -> f (m-1) 1
| m, n -> f (m-1) (f m (n-1))
;;
print_int (fix (acker 2 2));;
What do I need to do to get it to work? Thanks.
You are mixing curried with uncurried function definitions.
Here is acker in a consistently uncurried form:
let acker f = function
0, n -> n + 1
| m, 0 -> f (m - 1, 1)
| m, n -> f (m - 1, f (m, n - 1));;
Here is a call:
# fix acker (2, 2);;
- : int = 7
#
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.