Skip to content

Make maximumBy strict on the contents of its list

maximumBy uses too much stack when working on long lists:

Prelude Data.List> maximumBy compare [1..1000000]
*** Exception: stack overflow

Here's a fixed implementation; the only change is replacing foldl1 with foldl1'.

-- | The 'maximumBy' function takes a comparison function and a list
-- and returns the greatest element of the list by the comparison function.
-- The list must be finite and non-empty.
maximumBy               :: (a -> a -> Ordering) -> [a] -> a
maximumBy _ []          =  error "List.maximumBy: empty list"
maximumBy cmp xs        =  foldl1' maxBy xs
                        where
                           maxBy x y = case cmp x y of
                                       GT -> x
                                       _  -> y
Trac metadata
Trac field Value
Version 6.10.4
Type Bug
TypeOfFailure OtherFailure
Priority normal
Resolution Unresolved
Component libraries/base
Test case
Differential revisions
BlockedBy
Related
Blocking
CC
Operating system
Architecture
Edited by bdonlan@gmail.com
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information