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

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Christophe TROESTLER <debian00@t...>
Subject: Re: [Caml-list] Object typing
On Sat, 09 Jul 2005, "Matthew O'Connor" <angagon@earthlink.net> wrote:
> 
> Here is a version of what I would like to be able to do, but can't or
> don't know how.  I would like to use polymorphic variants to enable
> easier extensibility of the hierarchy.

To understand what does not work, try

class entity  =
object
  method is_a v = (v = `Entity)
end

You get an error message of which the important part is "The method
is_a has type ([> `Entity ] as 'a) -> bool where 'a is unbound".  It
says that the method [is_a] is of type 'a -> bool with a constraint on
'a.  Since you do not want a method of type (forall 'a) 'a -> bool
(written "'a. ([> ] as 'a) -> bool" in your error message), you
parametrize the class by that type 'a (the rest is in interactive
mode):

# class ['a] entity =
object
  method is_a (v:'a) = (v = `Entity)
end;;
  class ['a] entity :
  object constraint 'a = [> `Entity ] method is_a : 'a -> bool end

# class ['a] predator =
object
  inherit ['a] entity as super
  method is_a (v:'a) = (v = `Predator) || super#is_a v
end;;
  class ['a] predator :
  object
    constraint 'a = [> `Entity | `Predator ]
    method is_a : 'a -> bool
  end

# let ent = new predator;;
val ent : _[> `Entity | `Predator ] predator
# ent#is_a `Predator;;
- : bool = true
# ent#is_a `Entity;;
- : bool = true
# ent#is_a `Chicken;;
- : bool = false


P.S.  Notice the "_" in "_[> `Entity | `Predator ]".  It means that
the full type is yet to be determined.  Close it before the end of
your program.