Proposal: make minimumBy/maximumBy go through foldl', not foldr1

Lana Black lanablack at amok.cc
Wed Feb 10 20:07:22 UTC 2016


>  2 changing the behavior of Foldable.maximumBy (from foldr to foldl)
>    and changing the behavior of Data.List.maximumBy back to what it was before,
>    and arguably the “better” definition.
>  3 adding minimumBy/maximumBy as a class method and changing only the list instance.

The third option is the best, but I'd check for API breakages first.

> This also raises the question of whether using foldl over foldl' is the
> right thing to do, as I was under the impression that foldl will (at
> least for lists)  always just accumulate a large heap of thunks, and
> one would always want to use foldl' instead. I postulate that if foldl'
> had been in the report, then it would have been used for maximumBy.
> 

I tested maximumBy with foldl, and it runs in constant memory for lists,
so extra strictness won't have any benefits in this particular case. The
following snippet clearly shows it.

-----
main = print $ maximumBy compare [1..100000000000]

-- Copied from Data.Foldable with foldl1 replacing foldr1.
maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
maximumBy cmp = foldl1 max'
  where max' x y = case cmp x y of
                          GT -> x
                          _  -> y
-----


More information about the Libraries mailing list