I am finding it hard to find examples of on
in Haskell and I don't understand the explanation on Hoogle's Data.Function
page. Please, can I have examples of its use and examples of problems/code where using it makes a solution simpler or more efficient?
Suppose we have a function f
that takes two arguments. We want a similar function which acts as f
, but only after both its arguments have been modified by some other function g
.
We could write a new definition
new_f x y = f (g x) (g y)
or, exploiting on
,
new_f = f `on` g
Nicely, the latter can be used directly, without defining a new symbol new_f
. (Using a lambda is also viable, but not as nice)
This is typically used with compare
, a library binary function that checks the ordering between its two arguments. So, we can use
sortBy (compare `on` name) somePeopleList
sortBy (compare `on` age) somePeopleList
sortBy (compare `on` height) somePeopleList
...
to sort according different criteria. Above, we assume that name
, etc. are functions that can extract the relevant information from a person.
(In more modern Haskell we also have sortBy (comparing age) somePeopleList
, or even sortOn age somePeopleList
for the same task)