I have the following data structure and want it to be an instance of the typeclass Eq.
data Tree n l
= Node n (Tree n l) (Tree n l)
| Leaf l
I tried to do it the following way
instance Eq => (Tree n l) where
(Node a b c) == (Node d e f) = a == d
(Leaf a) == (Leaf b) = a == b
But there is an error message
‘==’ is not a (visible) method of class ‘Tree’
There are two problems here:
Tree n l
an instance; andn
and l
need to be types that are instances of the Eq
typeclass.So you can implement this with:
instance (Eq n, Eq l) => Eq (Tree n l) where
(Node a b c) == (Node d e f) = a == d
(Leaf a) == (Leaf b) = a == b
Note that now it will compile but there is still a problem: it will raise an error if you check if a Node … … …
is equal to a Leaf …
and vice versa. You can add an extra rule for that:
instance (Eq n, Eq l) => Eq (Tree n l) where
(Node a b c) == (Node d e f) = a == d
(Leaf a) == (Leaf b) = a == b
_ == _ = False
Here you will however consider two Node … … …
the same, from the moment they wrap the same value. So you do not look to the subtrees. In order to fix this, you need to perform recursion. I leave that as an exericse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With