if I specify the (I think) correct type for a high order function the OCaml compiler rejects the second usage of that function.
The code
let foo ():string =
let f: ('a -> string) -> 'a -> string = fun g v -> g v
in let h = string_of_int
in let i = string_of_float
in let x = f h 23
in let y = f i 23.0
in x ^ y
leads to the following error message
File "test.ml", line 6, characters 14-15: Error: This expression has type float -> string but an expression was expected of type int -> string
So the first usage of f
seems to fix the type of its first parameter to int -> string
. I could understand that. But what I don't get is that omitting the type restriction on f
fixes the problem.
let foo ():string =
let f g v = g v
in let h = string_of_int
in let i = string_of_float
in let x = f h 23
in let y = f i 23.0
in x ^ y
And moving f
to global scope fixes the problem, too:
let f: ('a -> string) -> 'a -> string = fun g v -> g v
let foo ():string =
let h = string_of_int
in let i = string_of_float
in let x = f h 23
in let y = f i 23.0
in x ^ y
Why is it that the first example does not compile while the later ones do?