Dude1662
Dude1662

Reputation: 41

Problem with type constructor in Haskell homework

I have created a datatype and need to make it an instance of the equality typeclass using instance. My datatype consists of values R a b. I want to make R x y equal to R c d if x is equal to c and y is equal to d.

Here is the code that I have written so far. It does not compile.

 data Row a b = R a b deriving (Show)
 instance Eq (Row a b)  where
     (R x y) == (R c d) = (x == c) && (y == d)
     _ == _ = False

I am thinking it might be wrong because the types a and b do not necessarily have to be in the Equality typeclass. I do not know how to fix this problem.

Upvotes: 4

Views: 83

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477853

You can only check if two R a bs are equal, given you can check that items of a and b are equal. So you need to add these as type constraints:

instance (Eq a, Eq b) => Eq (Row a b)  where
    (R x y) == (R c d) = (x == c) && (y == d)
    _ == _ = False

Note however that you do not need to implement the Eq instance yourself. If you want two R a bs to be the same if the data constructor is the same, and their corresponding parameters are the same, then you an just let the compiler derive the instance for your:

data Row a b = R a b deriving (Eq, Show)

Upvotes: 5

Related Questions