7. Data.Ord
The Ord
typeclass contains things that can be compared.
An Ordering
is one of three possible results:
LT
(less than) ifx<y
EQ
(equal) ifx==y
GT
(greater than) ifx>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, likecomparing
with a signaturea -> a -> Ordering
. -
sortOn
takes in a function of one argument, likeabs
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]