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-02 (08:39)
From: Jacques GARRIGUE <garrigue@m...>
Subject: Re: [Caml-list] Bug? Constraints get ignored in methods
From: Goswin von Brederlow <>

> I want to keep a linked list of structures that have a common subset
> of functionality. I thought this would be a good use of ocaml objects.
> A base class with the common subset of functionality and methods to
> link them. And then derived classes for the specific types. Most
> simplified it looks like this:
> # class type base_type = object val mutable next : base_type option method set_next : base_type option -> unit end;;
> # class foo = object inherit base method foo = () end;;
> # let a = new base in
>     let b = new foo in
>       a#set_next (Some (b :> base_type));;
> - : unit = ()
> I don't want to have to cast the objects
> all the time. So I thought there must be a better way using
> polymorphic methods with a constraint. But here is where everything
> breaks down. First lets look at just the set_next method:

>From your other posts I gather that your objects have a uniform
interface once they are in the list, and a specific interface just after
creating them. Hopefully you never need to recover the specific
interface from an object in a list (if that were the case, then I
strongly suggest using normal sum types...)

You don't want to write the coercions. That's natural. I see two ways
out. One is to realize that a method is just a weaker function, so
just write a function doing the coercion:

let set_next (x : #base_type) y =
  x#set_next (Some (y :> base_type))

You might not like using a function, but you just have to realize that
methods are kind of second class in ocaml...

If you really want to stick to methods only (because of library
design, for instance), then a clever trick is to use a coercion

class virtual base_type =
  object (self)
    val mutable virtual next : base_type option
    method virtual set_next_base : base_type option -> unit
    method as_base = (self :> base_type)
    method set_next : 'a. <as_base : base_type; ..> as 'a -> unit =
      fun x -> self#set_next_base x#as_base

This may seem verbose here, but self-coercion methods are a good idea

Hope this helps,

Jacques Garrigue