This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

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: 2007-11-09 (02:50) From: Jacques Garrigue Subject: Re: [Caml-list] a function for polymorphic and monomorphic objects
```From: Keiko Nakata <keiko@kurims.kyoto-u.ac.jp>
> Can I define a function taking as argument
> an object with a method, say, "map" whose type is instantiatable to
> (int -> int) -> int list?
>
> I have two object;
> one with a polymorphic map, the other with a monomorphic map.
>
> let p = object
>   method map : 'a.(int -> 'a) -> 'a list =  fun f -> List.map f [1;2;3]
> end;;
>
> let q = object
>   method map : (int -> int) -> int list = fun f -> List.map f [1;2;3]
> end;;
>
> I want to define a function like double below,
> which is applicable to both p and q.
>
> let double o = o#map (fun x -> x*2);;
>
> The only workaround I came up with is
>
> let double2 f = f (fun x -> x*2);;
> double2 p#map;;
> double2 q#map;;
>
> Yet this is not very nice....

Currently, this is the only workaround available.
A possibility once considered was to allow subtyping between the type
of p and the type of q. This way you could use your function double,
after applying a coercion for p.
However this is not so easy technically (mixing subtyping and
polymorphism...), and there has never been much demand for such
subtyping. Indeed, if one is required to do a (double) coercion
anyway, then double2 is not much worse (actually it is even shorter
here...)

Cheers,

Jacques Garrigue

```