Reputation: 41
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
Reputation: 477853
You can only check if two R a b
s 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 b
s 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