[Haskell-cafe] Where is "minimumsBy"?

Viktor Dukhovni ietf-dane at dukhovni.org
Wed Sep 26 15:03:53 UTC 2018


> On Sep 26, 2018, at 6:27 AM, Tom Ellis <tom-lists-haskell-cafe-2017 at jaguarpaw.co.uk> wrote:
> 
>  Actually what we
> want is more like
> 
>    minimumsBy :: ... => (a -> a -> Ordering) -> t a -> [a]
> 
> There can be many distinct minimizers.  For example when I want to get the
> collection of the youngest people from [(Age, Person)] I want
> 
>    minimumsBy (compare `on` fst) [(12, alice), (15, balaji), (12, cho)]
> 
> to return
> 
>    [(12, alice), (12, cho)]

It is a rather elementary function:

import Data.Foldable
import Data.Ord

-- Stable version that keeps the input order for elements that are
-- equal.  If this were to be a library function, I'd drop the
-- 'reverse' post-processing step, and leave the choice of stability
-- to the caller.
--
minimumsBy :: Foldable t => (a -> a -> Ordering) -> t a -> [a]
minimumsBy cmp xs = reverse $ foldl' acc [] xs
  where
    acc [] x = [x]
    acc mins@(m:_) x = case cmp m x of
        LT -> mins 
        EQ -> x:mins 
        GT -> [x]

-- 
	Viktor.



More information about the Haskell-Cafe mailing list