34

I'd like to sort by one property and then by another (if the first property is the same.)

What's the idiomatic way in Haskell of composing two comparison functions, i.e. a function used with sortBy?

Given

f :: Ord a => a -> a -> Ordering
g :: Ord a => a -> a -> Ordering

composing f and g would yield:

h x y = case v of
          EQ -> g x y
          otherwise -> v
        where v = f x y
  • 21
    Using Data.Monoid, you can get: f x y `mappend` g x y. – Vitus Jul 14 '12 at 18:50
51

vitus points out the very cool instance of Monoid for Ordering. If you combine it with the instance instance Monoid b => Monoid (a -> b) it turns out your composition function is just (get ready):

mappend

Check it out:

Prelude Data.Monoid> let f a b = EQ
Prelude Data.Monoid> let g a b = LT
Prelude Data.Monoid> :t f `mappend` g
f `mappend` g :: t -> t1 -> Ordering
Prelude Data.Monoid> (f `mappend` g) undefined undefined 
LT
Prelude Data.Monoid> let f a b = GT
Prelude Data.Monoid> (f `mappend` g) undefined undefined 
GT

+1 for powerful and simple abstractions

  • 4
    Woah... that is awesome. – huon Jul 14 '12 at 23:57
  • I knew that Haskell had to have an elegant solution to this :) Thank you for explaining it so clearly and concisely. – Alain O'Dea Jul 21 '12 at 2:53
  • This is brilliant. To sort a list of pairs: sortBy (comparing fst <> comparing snd) – dcastro Jan 20 '17 at 16:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.