If I understand you correctly, you mean that the lists are equal if the second element of each item is equal. That is, the comparison should be made only by the second element of the tuple.
In fact, the current code is comparing tuples and not just the second element. Like the tuple (2, 4)
is different from (1, 4)
the comparison already fails there.
To compare by the second element can be done as follows:
module Main where
listasIguais :: (Eq b) => [(a, b)] -> [(a, b)] -> Bool
listasIguais [] [] = True
listasIguais [] p = False
listasIguais p [] = False
listasIguais (x:xs) (y:ys) = (snd x) == (snd y) && (listasIguais xs ys)
emptyList = []::[(Int, Int)]
main = do
print $ listasIguais emptyList emptyList -- True
print $ listasIguais [] [(1,4),(2,6),(4,9)] -- False
print $ listasIguais [(2,4),(4,6),(8,9)] [(1,4),(2,6),(4,9)] -- True
Note that it was necessary to change the declaration of listasIguais
to assume that is a list of tuples.
Also note the use of snd
to take the second element of each tuple.
The statement of emptyList
is needed to help the compiler understand the type when the list is empty.
And it was missing to include the case of two empty lists. Without this equation, the function would always return False
because in the end it would fall into one of the two empty list equations that return False
.
Thank you, I’m clear
– João Sampaio
Don’t forget to vote and mark the answer as chosen :)
– Eric Chiesse