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

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: padiolea@i...
Subject: Re: [Caml-list] generic functions
> On Sun, 9 Jan 2005 wiedergaenger@fastmail.fm wrote:
>
>> I just got from LISP to OCaml, and wondered if there is an equivalent of
>> generic functions from LISP (CLOS) in OCaml. In the Common Lisp Object
>> System methods don't belong to certain objects/classes. They are just
>> function specializing on the argument types. So basically I want to
>> write something like:
>>
>> let foo (x : int) = x*x;;
>> let foo (x : float) = x*.x;;
>>
>> This, obviously, will not work since foo is just redefined by the second
>> statement. One would think, that having methods not being belonging to
>> objects/classes, is rather pointless. Well 95% of the time, there is no
>> necessity for that. But in the other 5%, it is really helpful.
>>
>
...

> 1) Just use different functions.  Do:
...

> 2) Use variant types:
...

> 3) Use modules:
...

I would add 4)  use objects.
see http://caml.inria.fr/ocaml/htmlman/manual005.html
and define a class ofloat, and oint (for object float and objects int)
and define
  let foo x = x#mul x
Note that foo does not have to belong to the classes. It can be defined
outside of the class defintion.
Of course if your definition of foo would have been
 let foo (x : int) = x+x;; (* * have been replaced by + *)
 let foo (x : float) = x*.x;;
then, it does not work anymore.



>
> With the exception of certain artificial contests (Paul Graham) I've never
> met a real world problem that needed overloading, or even benefitted
> signifigantly from overloading that didn't benefit just as much or more
> from one of the solutions above.

I guess that's because you never been involved in real world problems.
Overloading, which is adhoc polymorphism is as useful as
parametric polymorphism. Ask the haskell folks if they would accept
to forget about type classes.
Of course functors can emulate some of the advantages of overloading,
but not totally. Objects are better for this.

>
> Brian
>
>
> _______________________________________________
> Caml-list mailing list. Subscription management:
> http://yquem.inria.fr/cgi-bin/mailman/listinfo/caml-list
> Archives: http://caml.inria.fr
> Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
> Bug reports: http://caml.inria.fr/bin/caml-bugs
>