OCaml function type ('a -> 'b) -> 'a -> 'b

ocaml

Solution

The real problem is that the number of arguments of your try_it function is fixed.

You must understand correctly what goes on on this line:

print_endline(string_of_int(try_it add_two 23 45));;

try_it add_two 23 returns a function of type int -> int, which is in turn evaluated over the value 45, giving 23 + 45.

but if you change the definition of try_it as you did, then this line becomes:

print_endline(string_of_int(try_it 23 add_two 45));;

So that try_it 23 add_two returns a (int -> int) function, evaluated over 45.

Have a nice day !

Problem

I'm having some problems understanding how a function of this type works. ``` let try_it f x = f x;; val try_it : ('a -> 'b) -> 'a -> 'b = <fun> ``` The above function, try_it accepts a function f which accepts a polymorphic parameter and returns a polymorphic type. Now I can easily pass functions + parameters to try_it of varying number of parameters like below and it works. ``` let add_three a b c = a + b + c;; let add_two a b = a + b;; let try_it f x = f x;; print_endline(string_of_int(try_it add_two 23 45));; print_endline(string_of_int(try_it add_three 23 4 56));; ``` Now if the above works, why can't I create a function called try_it2 which is defined like below and pass it the same functions and parameters but in reverse order? ``` let try_it2 x f = f x;; val tryit2 : 'a -> ('a -> 'b) -> 'b = <fun> ``` To me try_it2 is the same as try_it with only the parameters order changed but I'm obviously missing something here. Can someone please put me on the correct path?

Original source