Version française
Home     About     Download     Resources     Contact us    
Browse thread
typeclasses in OCaml
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jacques Garrigue <garrigue@m...>
Subject: Re: [Caml-list] typeclasses in OCaml
From: Peng Zang <peng.zang@gmail.com>

> Recently however, I tried to make a "mappable" class.  Something like:
> 
>   class type ['a] mappable = object('self)
>     method map : 'z. ('a -> 'z) -> 'z 'self
>   end
> 
> Which of course is invalid syntax.  However, I think the point is clear.  I 
> want to specify the type of all container objects that can map their 
> contents.  How do you specify this in OCaml?
> 
> I realize there are some inherent issues, eg. polymorphic classes are 
> invarient.  So I'm willing to accept some limited use of magic as long as it 
> can be hidden away and offer a type-safe interface.  Nevertheless, after half 
> a day of trying, I cannot seem to figure this out.  I don't even know how to 
> specify:
> 
>   "  a 'z version of 'self  "
> 
> In a syntactically correct way.  Is this possible?  Thank in advance,
> 
> Peng

There is no way to specify "a 'z version of 'self", and this is the
reason you cannot do this in ocaml.

Even if you don't require structural polymorphism for your object type
(which you need here, since you want to write #mappable), there are
other difficulties related to recursive types having to be regular.

A classical workaround is to define map as a function using #fold and
cons:

let map cons f (o : 'a #foldable) =
  o#fold (fun x o' -> cons (f x) o')

Note that for this to work you need #fold to be the correct fold
(i.e. fold_right)

Hope this helps,

Jacques Garrigue