It's been hours and I can't understand this example in OCaml.
I don't know how to think about this so I'll try giving my process of thought.
The question is : For each definition or expression, give the type and value (<fun> included)
Here is the entire code (toplevel) :
let rec church_of_int n = if n = 0 then fun f x -> x else fun f x -> church_of_int (n-1) f (f x);; let three f x = church_of_int 3 f x;; three (fun x -> x + 1) 0;; three three (fun x -> x + 1) 0;; 1) First block
let rec church_of_int n = if n = 0 then fun f x -> x else fun f x -> church_of_int (n-1) f (f x);; This is a function which takes an int because of int operator "-" n-1 and returns a function which takes two arguments 'a and 'b. The function returned returns the same type of 'b because of the fun f x -> x.
Therefore the type is :
int -> ('a -> 'b) -> 'b = <fun> But the toplevel says :
val church_of_int : int -> ('a -> 'a) -> 'a -> 'a = <fun> I don't get it...
2) Second block
let three f x = church_of_int 3 f x;; For the second block, three takes a function and an int and applies it to the returned function of church_of_int.
Therefore, the type is :
('a -> 'b) -> int -> 'b = <fun> Toplevel says :
val three : ('a -> 'a) -> 'a -> 'a = <fun> 3) Third block
three (fun x -> x + 1) 0;; Here, we apply a function and an int to three.
We need to compute
church_of_int 3 (fun x -> x + 1) 0 church_of_int 3 = fun f x -> church_of_int 2 f (f x) church_of_int 2 = fun f x -> church_of_int 1 f (f x) church_of_int 1 = fun f x -> church_of_int 0 f (f x) church_of_int 0 = fun f x -> x THEN
church_of_int 1 = fun f x -> ((fun f x -> x) f (f x)) = fun f x -> f x church_of_int 2 = fun f x -> ((fun f x -> f x) f f(x)) = fun f x -> f (f x) church_of_int 3 = fun f x -> ((fun f x -> f (f x)) f f(x)) = fun f x -> f (f (f x)) therefore,
church_of_int 3 (fun x -> x + 1) 0 = 3 Toplevel confirms this is correct.
4) Fourth block
three three (fun x -> x + 1) 0;; Here it gets incredibly messy. On one side, we know that three (fun x -> x + 1) 0 = 3
then
three 3 is a partial application
on the other the toplevel returns 27.
Can you please help me fix my mistakes and my process of thought to get the correct types and results ?