[Haskell-cafe] Where is "minimumsBy"?

Hiromi ISHII konn.jinro at gmail.com
Wed Sep 26 14:52:02 UTC 2018


Not just a one-shot function, but you can do it with monoids:

```
import Data.Semigroup (Option(..), Semigroup(..))
import Data.DList

maximumsOn :: Ord b => (a -> b) -> [a] -> Maybe [a]
maximumsOn f = fmap (toList . elts) . getOption . foldMap (\a -> Option $ Just $ MaxAll (f a) $ pure a)
-- You don't need `Option`s since GHC 8.4

data MaxAll a b = MaxAll { weight :: a, elts :: DList b }
instance Ord a => Semigroup (MaxAll a b) where
  MaxAll l ls <> MaxAll r rs =
    case compare l r of
      EQ -> MaxAll l (ls <> rs)
      LT -> MaxAll l rs
      GT -> MaxAll r ls
```

> 2018/09/26 19:27、Tom Ellis <tom-lists-haskell-cafe-2017 at jaguarpaw.co.uk>のメール:
> 
> Data.List.minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
> 
>    https://www.stackage.org/haddock/lts-12.1/base-4.11.1.0/Data-List.html#v:minimumBy
> 
> but there are many cases where that's quite unhelpful.  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)]
> 
> Does "minimumsBy" exist somewhere reasonably standard?  Hoogle doesn't throw
> up anything obvious
> 
>    https://www.stackage.org/lts-12.1/hoogle?q=%28a+-%3E+a+-%3E+Ordering%29+-%3E+t+a+-%3E+%5Ba%5D
> 
> Thanks,
> 
> Tom
> _______________________________________________
> Haskell-Cafe mailing list
> To (un)subscribe, modify options or view archives go to:
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
> Only members subscribed via the mailman list are allowed to post.

----- 石井 大海 ---------------------------
konn.jinro at gmail.com
筑波大学数理物質科学研究科
数学専攻 博士後期課程三年
----------------------------------------------

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 488 bytes
Desc: Message signed with OpenPGP
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20180926/71129973/attachment.sig>


More information about the Haskell-Cafe mailing list