Trouble instancing Eq in my Relation data type

Viewed 47

I'm stuck instancing the following:

data Rel a = R [(a,a)] deriving (Read, Show)

listaPares:: Rel a -> [(a,a)]
listaPares (R rel) = rel

instance Eq (Rel a) where
    x == y = ((fst $ listaPares x == fst $ listaPares y) && (snd $ listaPares x == snd $ listaPares y))

Rel is a datatype that holds a list of tuples, and the elements inside the tuples can be anything, from an integer, a char or even a list.

My method listaPares takes a type Rel and returns the list of tuples so I can manipulate the list.

Thing is I'm really stuck instancing my data type's Eq. What I'm doing right now is getting the first element of the x tuple and check if its identical to the first element of the y tuple and so on, but since a could be a list, a simple (==) wouldn't really work, right?

Any tips are highly appreciated!

1 Answers

Why don't you write:

data Rel a = R [(a,a)] deriving (Read, Show, Eq)

It works just fine.

As far as list equality, there is in fact an instance of Eq a => Eq [a]. There's also (Eq a, Eq b) => Eq (a, b), which in your case could be simplified to Eq a => Eq (a,a).

So if Eq a holds, then Eq (a,a), and thus Eq [(a,a)] hold as well and can be derived.

In your manually written attempt, you in fact forgot the Eq a constraint, which is necessary for it to work at all. It doesn't really matter what a is, it could be a list, as long as the type of the element of the list also has an Eq instance and so on.

Related