7. Data.Ord

The Ord typeclass contains things that can be compared.

An Ordering is one of three possible results:

  • LT (less than) if x<y
  • EQ (equal) if x==y
  • GT (greater than) if x>y

The compare x y function takes in two Ord things gives an Ordering.

The normal use of Ord is in sorting. The Data.List module has several sorting functions.

  • sort

  • sortBy takes in a function of two arguments, like comparing with a signature a -> a -> Ordering.

  • sortOn takes in a function of one argument, like abs that outputs something that can be ordered.

      sortOn  abs [-10,30,-60,5] == [5,10,30,60]
    

The Down type creates a new thing that sorts the opposite of the original’s natural direction.

sortOn Down [1,5,3,6,10] == [10,6,5,3,1]

The comparing function creates a comparison after applying a function.

sortBy (comparing abs) [-10,30,-60,5] == [5,10,30,60]