Doubt in case of Stop

Asked

Viewed 41 times

1

listasIguais :: (Eq a) => [a] -> [a] -> Bool

listasIguais [] p = False

listasIguais p [] = False

listasIguais (x: xs) (y:ys) = x == y && (listasIguais xs ys)

listasIguais [(2,4),(4,6),(8,9)] [(1,4),(2,6),(4,9)]
False

This result should be true. I think I was wrong in the case of stopping. Can you tell me what my mistake is ?

1 answer

1

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

  • Don’t forget to vote and mark the answer as chosen :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.