I have this data type and I want to define a equality operator for it. Mlist should be an instance of Eq.
data Mlist a = Mlist [a]
instance Eq a => Eq (Mlist a) where
(==) :: [a] -> [a] -> Bool
The equality operator should allow me to check this (plus the ordering shouldn't matter):
m1 = Mlist [1,2,3]
m2 = Mlist [3,1,2]
-- then m1 equals m2
m3 = Mlist [3,2,1,5]
-- then m1 not equals m3
The top code isn't working, can anyone help with this?
Edit: Here is a new version, but it's not working...
instance Eq a => Eq (Mlist a) where
(==) :: (Eq a) => [a] -> [a] -> Bool
(==) [] [] = True
(==) [] _ = False
(==) _ [] = False
(==) (hd:tl) b = (==) tl $ delete hd b
To make Mlist a
an instance of Eq
, you have to define either
(==) :: Mlist a -> Mlist a -> Bool
or
(/=) :: Mlist a -> Mlist a -> Bool
In essence, you need to implement a function which can determine whether two lists equal. Since Eq
is the only constraint, you can use the help from Data.List.\\
. For example:
instance Eq a => Eq (Mlist a) where
Mlist xs == Mlist ys = length xs == length ys && null (xs \\ ys)
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