tags:

views:

146

answers:

3

Trying to create a base class from which I can derive different types. What's wrong with the following?

class (Eq a) => MyClass a 

data Alpha = Alpha
instance MyClass Alpha where
    Alpha == Alpha = True

I get the error:

test.hs:5:10: `==' is not a (visible) method of class `MyClass'
Failed, modules loaded: none.
+7  A: 

You have to make Alpha an instance of Eq explicitly. This will work:

data Alpha = Alpha
instance Eq Alpha where
    Alpha == Alpha = True
instance MyClass Alpha
sepp2k
Thanks. So if I have a string of inheritance, I have to instantiate each of the derived classes and cannot do them all in one go?
me2
Correct, but you should think of it more like "if a wants to instantiate MyClass, it first needs to instantiate Eq" than like inheritance.
sepp2k
+2  A: 

The first line says that you need to declare Alpha an instance of Eq first, then of MyClass.

Paul Johnson
+1  A: 

Based on the structure of the question, it seems that you're expecting Haskell typeclasses to behave in a manner similar to classes in an object-oriented language. Typeclasses are more like Java interfaces.

There is no inheritance. A typeclass is simply a description of a set of functions that are implemented for a type. Unlike a Java interface, those functions can be defined in terms of each other, so that a minimally complete instance declaration may only need to define some of the functions.

Zak