Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a equality operator for a class in Haskell?

Tags:

haskell

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
like image 349
omega Avatar asked Jan 15 '23 00:01

omega


1 Answers

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)
like image 125
nymk Avatar answered Jan 28 '23 05:01

nymk