Browse thread
type of high order functions
- Alexander Bernauer
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Alexander Bernauer <bernauer@i...> |
| Subject: | type of high order functions |
Hi
if I specify the (I think) correct type for a high order function the
OCaml compiler (version 3.11.2) rejects the *second* usage of that function.
The code
---8<---
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
--->8---
leads to the following error message
---8<---
File "test.ml", line 6, characters 14-15:
Error: This expression has type float -> string
but an expression was expected of type int -> string
--->8---
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.
---8<---
let foo ():string =
let f = 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
--->8---
And moving f to global scope fixes the problem, too:
---8<---
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
--->8---
Why is it that the first example does not compile while the later ones do?
regards
Alex