Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

[Haskell-cafe] type classes

1 view
Skip to first unread message

Peter Padawitz

unread,
Dec 14, 2007, 7:30:03 AM12/14/07
to haskel...@haskell.org
I'd like to define several instances of the same type class with the
same type variable instance. Only method instances differ. How can I do
this without writing copies of the type class?

_______________________________________________
Haskell-Cafe mailing list
Haskel...@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Lutz Donnerhacke

unread,
Dec 14, 2007, 8:12:30 AM12/14/07
to haskel...@haskell.org
* Peter Padawitz wrote:
> I'd like to define several instances of the same type class with the
> same type variable instance. Only method instances differ. How can I do
> this without writing copies of the type class?

Define the type class in a module named "MyClass". Define the each instance
in a module named "MyInstanceX" where X is a version number.

Include only the "MyInstanceX" module, you currently need.

Ketil Malde

unread,
Dec 14, 2007, 9:02:08 AM12/14/07
to Lutz Donnerhacke, haskel...@haskell.org
Lutz Donnerhacke <lu...@iks-jena.de> writes:

> * Peter Padawitz wrote:
>> I'd like to define several instances of the same type class with the
>> same type variable instance. Only method instances differ. How can I do
>> this without writing copies of the type class?

> Define the type class in a module named "MyClass". Define the each instance
> in a module named "MyInstanceX" where X is a version number.

> Include only the "MyInstanceX" module, you currently need.

Or, if you need more than one at the same time, wrap your data type in
one newtype per instance.

-k
--
If I haven't seen further, it is by standing in the footprints of giants

Jules Bean

unread,
Dec 14, 2007, 9:48:50 AM12/14/07
to Peter Padawitz, haskel...@haskell.org
Peter Padawitz wrote:
> I'd like to define several instances of the same type class with the
> same type variable instance. Only method instances differ. How can I do
> this without writing copies of the type class?

newtypes and modules have both been suggested.

I have another suggestion:

Don't!

Don't use typeclasses.

The only useful thing about typeclasses is that they are a kind of
type-indexed family of dictionaries. If you don't want to use the type
indexin, then don't use classes. Just use your own kind of dictionary.

E.g., instead of:


class Foo a where { bar :: a -> Int; baz :: a -> String }

instance Foo Double ...
instance Foo Double ... -- bother, I wanted a different Double instance!


you should just have:

data Foo a = Foo { bar :: a -> Int, baz :: a -> String }

foo1 :: Foo Double
foo1 = Foo { ... }

foo2 :: Foo Double
foo2 = Foo { ... }

-- now I can have as many 'instances' for the same type as I want!

Jules

0 new messages