Version française
Home     About     Download     Resources     Contact us    

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

Browse thread
Bug? Constraints get ignored in methods
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2009-04-01 (03:25)
From: Goswin von Brederlow <goswin-v-b@w...>
Subject: Re: [Caml-list] Bug? Constraints get ignored in methods
Peng Zang <> writes:

> Hi,
> Here's an example of how constraints are specified for polymorphic methods.  
> In this example I define a list type which can compare to anything that is 
> foldable.
>   class type ['a] foldable = object
>     method foldl : 'z. ('z -> 'a -> 'z) -> 'z -> 'z
>   end
>   class type ['a] mylist = object
>     inherit ['a] foldable
>     method compare : 'z. ('a #foldable as 'z) -> int
>   end
> Direct application to your example would not work:
>   # class virtual base = object
>       method virtual setnext : 'a. (#base as 'a) option -> unit
>     end
>   Error: This type scheme cannot quantify 'a : it escapes this scope.
>   #
> OCaml does not allow the recursive reference when the method is polymorphic.  
> One option is to just deal with coercions or a function that does it for you:
>   class virtual base = object
>     method virtual setnext : base option -> unit
>   end
>   let callsetnext (obj:#base) (n:#base option) = 
>     obj#setnext (n :> base option)

That is the part I wanted to clean up / simplify. Doesn't look nice if
some methods are called with # and others need the wrapper function.

> Another option is to factor out the basic operations you need like the in list 
> example.  I didn't make the list compare method work with other lists, I made 
> it more general to work with anything that is foldable.  This avoids the 
> recursive reference because foldable is defined ahead of time.

That was what I did except with virtual methods where the implementation is
type specific.

> Cheers,
> Peng

So something like this:

class type linked = object val mutable next : #linked option end
class type base_type = object
  inherit linked
  method set_next : 'a. (#linked as 'a) option -> unit

That could actually work. I hope. Thanks.