Comparing lists in Haskell, or more specifically what is lexicographical order?

Viewed 10087

I'm just beginning this nice hashkell beginners tutorial:

http://learnyouahaskell.com

on this page on lists he explains that lists are compared in compared in lexicographical order, he gives this example:

ghci> [3,2,1] > [2,10,100]
True

From some googling it seems to me that lexicographical ordering means in alphabetical or sequential number ordering(?), but I still can't make sense of this evaluating to True.

I'm missing something obvious here, can anybody help?

6 Answers

Example:

What happens when walking through the following?

[1,2,9,2] > [1,2,10,1] -- False

[ 1, 2, 9, 2]

[ 1, 2,10, 1]

  1. compare 1 > 1, equal? yes, continue to next comparison
  2. compare 2 > 2, equal? yes, continue to next comparison
  3. compare 9 > 10, equal? no, 9 is actually less, stop and return False

Other examples

[1,2,9,2] < [1,2,10,1] -- True

[1,2,3,4] <= [1,2,3,5] -- True

[1,2,3,4] >= [1,2,3,4] -- True

[1,2,3,4] <= [1,2,3,4] -- True

I think LearnYouAHaskell would benefit from writing the word Only.

First the heads are compared. *Only* if they are equal then the second elements are compared, etc.

So because 3 is greater than 2, the decision is complete and there is no need to check indexes 1 and 2.

[3,2,1] > [2,10,100] == [3] > [2]

It can also be thought of a bit like a sortable date

2019-07-06 > 2011-08-09

If you do that in your head, you checked the years first, and don't need to check the months or days now to know the the first date is greater.

Just understand this: comparing two lists doesn't mean comparing the values of all the elements in each list. Rather it means simply comparing the lexical order of each element in list1 with the corresponding element in list2, and returning the result as soon as it found that the two elements are ordered differently lexically.

Related