English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
oo type question
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2008-03-10 (08:21)
From: Jacques Garrigue <garrigue@m...>
Subject: Re: [Caml-list] oo type question
From: Michael Wohlwend <micha-1@fantasymail.de>
> Am Donnerstag, 6. März 2008 14:18:29 schrieb Peng Zang:
> > BUT, what I think you really want is a polymorphic method, not a
> > polymorphic class.  The manual has a decent explanation under polymohrphic
> > methods in the Objects section.  So I think you want this:
> >   method add : 'a. <id:int; ..> as 'a -> unit =
> >     fun o -> ids <- o#id :: ids
> I know that version and of course it works. I only  didn't understand (and 
> still do not) why it's not possible to just declare
> method add (a: #someClass) ... which seems natural for me. And it works for 
> normal functions that way.
> If you have many classes (actually it's for adding widgets to group widgets) 
> it seems just a bit too complicated and not a natural way to declare such a 
> simple thing.

One reason it is not so simple for methods is that they belong to
objects. So if you write
   method add (a : #someClass) ...
which is really equivalent to
   method add (a : <some methods; .. > as 'a)
it is not clear where the variable should be bound. This could be
either at the class level (for the whole object, as in your first
example) or at the method level. So you need an explicit syntax to
tell which one it is to the type system.

Another reason, a bit more technical, is that polymorphic methods do
not behave like polymorhic functions. In particular, they cannot be
instantiated automatically when needed: i.e., you cannot pass an
object with a polymorphic method where a monomorphic method is
expected. Currently, even subtyping is not allowed between polymorphic
methods and their monomorphics instances (this may change in 3.11).
So this seems a bad idea to create a potentially incompatible
polymorphic method without some explicit direction from the
programmer. Note that the type annotation #someClass is not sufficient
direction, because it does not request any polymorphism: it is not an
error for the actual method to be of type "someClass -> ..." (I'm not
sure it is what most people expect, but it is the way ocaml is

A small remark yet: in interfaces (and class types) it is ok to write
  class c : object
    method add : #someClass -> ...
Here it is automatically assumed that the type variable is bound at
the method level.

Jacques Garrigue