[Haskell-cafe] Specializing classes with classes

Andrew Coppin andrewcoppin at btinternet.com
Sat Dec 29 05:28:11 EST 2007

alex wrote:
> Hi, I am new to everything Haskell and am stumped on
> an aspect of Type Classes.
> I would like to do this:
>     class Foo t where
>         hi :: t -> Bool
>     class Foo t => Bar t where
>         hi x = True
> But using GHC 6.8.1 on PPC I get this error:
>     `hi' is not a (visible) method of class `Bar'

You can't do that. (Well, you just discovered that!)

When you say "class Foo t => Bar t", what you're saying is that no type 
can belong to "Bar" until it belongs to "Foo" first. And that is all. 
Remember, in Haskell any given type can belong to any number of classes 
all at once. All the definition there says is that you have to add a 
type to Foo before you can add it to Bar. You still have to write two 
[seperate] instance declarations.

It's not like OOP where every Bar *is* a Foo. They remain seperate. You 
just need to have one before you can have the other. Beyond that, they 
share nothing.

[Well, the default methods for Bar can mention methods in Foo. But 
that's about it.]

One might hope, for example, that you could define a "Vector" class, and 
make it so that anything that is a member of Vector is automatically a 
member of Num. Sadly, this is impossible. Even if each instance 
declaration is identical but for the type names, you must still write 
out each definition seperately. Pitty...

More information about the Haskell-Cafe mailing list