Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
Typeclasses in OCaml (Was: Haskell vs OCaml)
[ 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] Typeclasses in OCaml (Was: Haskell vs OCaml)
Hash: SHA1

On Thursday 14 August 2008 12:04:23 pm Jim Farrand wrote:
> This doesn't answer my question at all.  :)
>  Is there any theoretical reason they couldn't added?  The kind of
> answer I'm looking for is "There is no theoretical reason why not", or
> "This is impossible as it would cause typing in OCaml to become
> undecidable, due to interactions with other features of the OCaml type
> system which aren't present in Haskell."

Oh yeah... oops.  But to answer your question, it appears to be "yes you can":

It's not pretty as you have to pass the dictionary by hand, but perhaps some 
camlp4 magic could easy that.  Also, the example given is of rather simple 
type classes, I'm not sure about the full blown thing.

> Though, to address your solution, I am of course aware of it, but it
> has what seem like big disadvantages:
> 1. Every value in OCaml would then have to be an object
> 2. Every comparison now requires a relatively expensive dynamic
> dispatch, when the correct function could be determined at runtime.
> 3. If I add a new operator that wasn't thought of by the language
> implementors, it can't be easily added to primitive values, without
> either subclassing all of them, or changing the definition in the
> standard library to add the new method.

1 & 2 are performance concerns that can be addressed as follows:  Let's still 
have polymorphic operators like (=) and "compare".  They will perform their 
normal operation on basic types.  On objects, they will call the object's 
appropriate method.  I have implemented this approach and use it in my own 
code.  It let's me avoid wrapping everything in an object which lets me avoid 
a lot of dynamic dispatches.  (the dispatches are cached so its cost is 
further diluted)

I don't know what to do about 3.  I haven't encountered it thus far.  
Actually, I don't know how type classes help you out here.  Wouldn't you 
still have to modify the type definition of Ints and Floats and whatever 
other standard type to add the new operation?

Version: GnuPG v2.0.7 (GNU/Linux)