Compare items from two lists in Haskell

0

I have tried to compare elements belonging to two lists in Haskell and I do not understand the result obtained.

Cito de aprendehaskell.es :

  

Lists can be compared if the items they contain can be compared. When we use & lt ;, < =, & gt ;, and > = to compare lists, they are compared in lexicographical order. First the heads are compared. Then the second elements are compared and so on.

I decided to try the following comparison in the WinGHCI compiler:

Prelude> [1,2,3] < [4,5,2]

The result obtained was: True

What I understood from the quote, is that when comparing in lexicographical order, first compare 1 with 4, and as 1 < 4, it is true, then compare 2 with 5, and as 2 < 5 true, but when comparing 3 < 2, false should come out. So the result that I expected was false. However, I get true.

The question is, Haskell only compares the first element and does not compare the rest, or does he compare the first first, then the second ...? BUT do you always keep the result of the first one? which would be absurd, since it would not make sense to carry out the rest of operations since the result will not vary.

Thanks

    
asked by OnlyDavies 05.09.2018 в 18:29
source

1 answer

0

When two lists are compared by lexicographical order, they are compared element by item until one of them differs , or until the elements of either list are finished (in which case all the elements so far were equal and the list with fewer elements is smaller). This is not a special feature of Haskell, other languages such as Python implement the same criteria.

Therefore, in your example [1,2,3] < [4,5,2] the first list is less than the second, because the first element of the first is already smaller than the first element of the second. If the lists were [4,5,2] < [4,5,1] , since the first two elements of both lists are equal, the 2 would be compared with the 1 , determining that the first list is greater than the second.

The comparison that you expect, where all the elements must be major, minor, etc., you can get it for example, comparing the elements with zipWith :

zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]

zipWith takes a function (in this case (<) , (>) , (<=) or (>=) ) and two lists, and combines the lists by applying this function. For example:

ghci> zipWith (<) [1,2,3] [4,5,2]
[True, True, False]

Finally, you can use the function and :: Foldable t => t Bool -> Bool to check that all the elements in the list are True , that is, that all the elements satisfy the order relation applied element by element.

ghci> and $ zipWith (<) [1,2,3] [4,5,2]
False
ghci> and $ zipWith (<) [1,2,3] [4,5,6]
True
ghci> and $ zipWith (>=) [1,2,6] [1,2,1]
True
    
answered by 06.09.2018 / 00:30
source