No instance for (Eq a) arising from a use of ‘==’

  • A+
Category:Languages

I'm trying to write an Eq instance for this data type:

data Tree a b = Leaf b | Node a (Tree a b) (Tree a b) deriving (Show) 

I wrote the trivial code I thought that would work:

instance Eq (Tree a b) where   (Leaf x) == (Leaf y) =  x == y   (Node val1 l1 r1) == (Node val2 l2 r2)  =  (val1 == val2) && (l1==l2) && (r1==r2)   _  == _  = False 

But then I get the error:

• No instance for (Eq a) arising from a use of ‘==’   Possible fix: add (Eq a) to the context of the instance declaration • In the first argument of ‘(&&)’, namely ‘(val1 == val2)’   In the expression: (val1 == val2) && (l1 == l2) && (r1 == r2)   In an equation for ‘==’:      (Node val1 l1 r1) == (Node val2 l2 r2)      = (val1 == val2) && (l1 == l2) && (r1 == r2) 

I've tried adding Eq a => ... but then I get the same error for type b. And I can't seem to add Eq b as well.

Any help will be appreciated, 10x!


As you have written, you have to put type constraints Eq a and Eq b. You just have to put the constraints in parentheses and separate them with comma.

instance (Eq a, Eq b) => Eq (Tree a b) where   (Leaf x) == (Leaf y) =  x == y   (Node val1 l1 r1) == (Node val2 l2 r2)  =  (val1 == val2) && (l1==l2) && (r1==r2)   _  == _  = False 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: