Version française
Home     About     Download     Resources     Contact us    
Browse thread
a function for polymorphic and monomorphic objects
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Andrej Bauer <Andrej.Bauer@f...>
Subject: Re: [Caml-list] a function for polymorphic and monomorphic objects
Keiko Nakata wrote:
> Can I define a function taking as argument 
> an object with a method, say, "map" whose type is instantiatable to
> (int -> int) -> int list?

Don't write too many type annotations by hand and everything will be 
fine. In your case you got it wrong when you quantified 'a in the object p.

         Objective Caml version 3.09.3

# let p = object method map =  fun f -> List.map f [1;2;3] end;;
val p : < map : (int -> 'a) -> 'a list > = <obj>
# let q = object method map = fun (f : int -> int) -> List.map f [1;2;3] 
end;;
val q : < map : (int -> int) -> int list > = <obj>
# let double o = o#map (fun x -> x*2);;
val double : < map : (int -> int) -> 'a; .. > -> 'a = <fun>
# double p;;
- : int list = [2; 4; 6]
# double q;;
- : int list = [2; 4; 6]


I think the general hint is this: first try without type annotations. 
Then, if you're not happy (say because the function is "too 
polymorphic") add as few type annotations as possible, e.g., annotate f 
above rather than map.

Best regards,

Andrej