[Haskell-cafe] A small oversight

Andrew Coppin andrewcoppin at btinternet.com
Sat Feb 20 05:47:30 EST 2010

I just discovered the highly useful function Data.Function.on. I vaguely 
recall a few people muttering a couple of years back that this would be 
a useful thing to have, but I had no idea it was in the standard 
libraries now.

Anyway, while using it, I discovered a small omission from the Haskell 
libraries: We have min, max, minimum and maximum. We also have minimumBy 
and maximumBy. But there's no sign of minBy or maxBy. You can do, for 

  (min `on` postcode) customer1 customer2

but that gives you the lowest postcode, not the customer to which this 
postcode belongs. By contrast,

  minimumBy (compare `on` postcode) [customer1, customer2]

gives you the corresponding customer. But it seems silly to have to 
actually construct a list just for this. So... is there any danger of 
getting minBy and maxBy added? (I don't actually know off the top of my 
head where min and max are defined - the Prelude?)

Also, constructions like

  sortBy (compare `on` foo)

must surely be very common. Perhaps it would be an idea to define a 
family of functions like

  sortOn :: (Ord y) => (x -> y) -> [x] -> [x]
  sortOn foo = sortBy (compare `on` foo)

Just an idea.

Finally, take a look at this:

  newtype SwapOrd x = SwapOrd (unswap_ord :: x) deriving Eq

  instance Ord x => Ord (SwapOrd x) where
    compare x y = swap_ord $ compare x y

  swap_ord :: Ordering -> Ordering
  swap_ord o = case o of
    EQ -> EQ
    GT -> LT
    LT -> GT

Just in case you wanted to sort things in reverse order. I think having 
swap_ord would be nice if nothing else...

More information about the Haskell-Cafe mailing list