[Haskell] Annoying naming clashes

Georg Martius mai99dgf at studserv.uni-leipzig.de
Tue Jun 15 09:06:54 EDT 2004


On Tue, 15 Jun 2004 12:05:46 +0100, Graham Klyne <GK at ninebynine.org> wrote:

> At 11:30 15/06/04 +0200, Wolfgang Jeltsch wrote:
>> I'd say, classes in Haskell are similar to interfaces in Java.
>
> I started my Haskell programming with that viewpoint, but got tripped up by it.
>
> A Java interface can be used as a type in its own right, but a Haskell
> class cannot.  For example, you can't have a list of Eq's, only a list of
> some type that happens to be an Eq.  The different list members can't be
> differently-typed instances of Eq.
Well, just with existential types.

> To emulate a Java interface, I have ended up creating algebraic data types
> whose components are functions.  (I don't claim that's a good approach to
> Haskell programming, just what I ended up doing.)

My approach was to create an existential types for each class and instanciate it from the class like:

class FooClass f where
   bar :: f -> Integer
   setBar :: Integer -> f -> f

data Foo = forall f . FooClass f => Foo f

instance FooClass Foo where
	bar (Foo f) = bar f
	setBar b (Foo f) = Foo $ setBar b f

I am not sure if this is the way to go, but at least it works (except for read issues). The advantage I see in this approach is that I can stick all types that are instanciated from FooClass in a list and can deal with them as there would be no exitential type constructor "in the way".

Cheers,
  Georg


More information about the Haskell mailing list