Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] does class polymorphism need to be so complicated?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Benjamin Geer <ben@s...>
Subject: Re: [Caml-list] does class polymorphism need to be so complicated?
Brian Hurt wrote:
> Instead of declaring obj to be printable, why not just declare that it has 
> a function print?  Like:
> 
> class printer = 
>     object
>         method print (obj: <print: unit->unit>) = obj#print ();
>     end;;
> 
> This removes the need for a coercion, as it gets around the need to 
> upcast.

That's pretty cumbersome, because it will have to be repeated for every 
method that uses an object of that type.  And suppose you need the 
method's argument to be an object with several methods.  You could end 
up writing methods like this:

class thing_processor =
    object
      method do_something (t : obj: <foo: int->int;
                                     bar: unit->string;
                                     baz: unit->bool ;
                                     quux: unit->unit>) =
        (* do something that calls all those methods *)

      method do_something_else (t : obj: <foo: int->int;
                                          bar: unit->string;
                                          baz: unit->bool;
                                          quux: unit->unit>) =
        (* do something else that calls all those methods *)
  end;;

It would seem natural to define an interface as a shorthand, and to use 
it like this:

class type thing =
    object
      method foo : int -> int
      method bar : string
      method baz : bool
      method quux : unit
  end;;

class thing_processor =
    object
      method do_something (t : #thing) =
        (* do something that calls all those methods *)

      method do_something_else (t : #thing) =
        (* do something that calls all those methods *)
  end;;

But alas, this is not valid in Caml.

Ben

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners