Why are `sum` and `product` defined via foldMap' and not foldl'?

Viktor Dukhovni ietf-dane at dukhovni.org
Wed Dec 23 06:32:38 UTC 2020


Is there a compelling reason for:

    sum = getSum #. foldMap' Sum
    product = getProduct #. foldMap' Product

rather than:

    sum = foldl' (+) 0
    product = foldl' (*) 1

A quick ghci session with today's GHC head yields:

    λ> import qualified Data.Foldable as F
    λ> :set +s

    λ> F.sum [0..10000000]
    50000005000000
    (2.98 secs, 1,612,368,368 bytes)

    λ> F.foldl' (+) 0 [0..10000000]
    50000005000000
    (0.28 secs, 880,065,112 bytes)

The `foldl'` variant looks substantially more efficient (at least for
lists), is there some important context in which `foldMap'` is
preferable?

-- 
    Viktor.


More information about the Libraries mailing list