Version française
Home     About     Download     Resources     Contact us    
Browse thread
type of high order functions
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Alain Frisch <alain@f...>
Subject: Re: [Caml-list] type of high order functions
On 12/14/2010 09:30 PM, Alexander Bernauer wrote:
> 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---

The scope for type variables is implicitly defined as the smallest 
surrounding structure item. In your case, the scope for 'a is the "let 
foo..." declaration, not the local declaration "let f".

There are two solution to do what you want in OCaml 3.12.

* Use the syntax introduced for polymorphic recursion:

   let f: 'a. ('a -> string) -> 'a -> string = fun g v -> g v

* Create a locally abstract type:

   let f (type a) (g : a -> string) (v : a) : string = g v




-- Alain