me2
me2

Reputation: 754

How to properly instantiate classes in Haskell?

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.

Upvotes: 4

Views: 4683

Answers (3)

Zak
Zak

Reputation: 1167

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.

Upvotes: 1

Paul Johnson
Paul Johnson

Reputation: 17786

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

Upvotes: 2

sepp2k
sepp2k

Reputation: 370212

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

Upvotes: 9

Related Questions