[Haskell-cafe] A small oversight
Ben Millwood
haskell at benmachine.co.uk
Sat Feb 20 07:39:24 EST 2010
I can't answer your question (about getting minBy into the libraries)
but I thought I'd point out some tricks:
On Sat, Feb 20, 2010 at 10:47 AM, Andrew Coppin
<andrewcoppin at btinternet.com> wrote:
> Also, constructions like
>
> sortBy (compare `on` foo)
>
> must surely be very common.
Common enough that Data.Ord introduces comparing:
comparing :: (Ord a) => (b -> a) -> b -> b -> Ordering
comparing = (compare `on`)
see http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Ord.html#v%3Acomparing
But it would still be useful to have sortOn et al to capture the
common technique when your sorting property is potentially expensive
(sortOn length, for example):
sortOn f = map fst . sortBy (comparing snd) . map (\x -> (x, f x))
a technique which I believe is called a Schwarzian transform.
> 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...
>
swap_ord (compare x y) = compare y x, so usually flip compare fills
this requirement :)
More information about the Haskell-Cafe
mailing list