Version française
Home     About     Download     Resources     Contact us    
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: -- (:)
From: Peng Zang <peng.zang@g...>
Subject: Re: [Caml-list] oo type question
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Thursday 06 March 2008 10:45:30 am Michael Wohlwend wrote:
> Am Donnerstag, 6. März 2008 14:18:29 schrieb Peng Zang:
> > let s = new store ;;
> > s#add (o1 :> <id:int>);;
> > s#add (o2 :> <id:int>);;
> >
> > Note how I coerce o1 and o2 both to a subtype before adding.  Now the
> > problem goes away because to the s#add method o1 and o2 have the same
> > type.
>
> yes, that's the easy way, but then I have to do casts all over the place,
> not very nice
>
> > 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.

Hmmm... I do not know of another easy way to do this.  Polymorphic methods 
cannot be inferred in general because IIRC it is undecidable?  That said, 
this special case seems simple enough.

Other (possibly lame) suggestions:

1) You can give some nice type alias to "<id:int; ..> as 'a" so the type 
specification looks simpler

2) You can go with the polymorphic class case and write a small helper 
function, eg:

  let addwithcoerce s a = s#add (a :> <id:int>)

to hide the coercions.

Perhaps others on this list will have additional ideas too.

Regards,
Peng


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.7 (GNU/Linux)

iD8DBQFH0CKmfIRcEFL/JewRAkLXAKCLog1BC8wViOJ+yF/TjoG4T+5KDACgxXJ1
HiUc6i+D9bvpKWn/zCbWEf0=
=R6fR
-----END PGP SIGNATURE-----