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

Oleg Grenrus oleg.grenrus at iki.fi
Wed Dec 23 12:55:45 UTC 2020


I stand corrected.
https://gitlab.haskell.org/ghc/ghc/-/merge_requests/4355 is merged

and seems I misread the original e-mail.

Foldable should prefer foldMap' (or foldMap) because it offers most
opportunities (Monoid mappend is associative). Trees, SnocList work
better by default.

For lists the implementation could use foldl', because in that special
case it makes more sense.

These methods (sum, product) are part of Foldable class specifically so
they can be overriden.

- Oleg

On 23.12.2020 12.44, Oleg Grenrus wrote:
> Because the related change proposal(s) are never accepted nor implemented.
>
> Most recent one is quite recent though.
> https://mail.haskell.org/pipermail/libraries/2020-October/030862.html
>
> - Oleg
>
> On 23.12.2020 8.32, Viktor Dukhovni wrote:
>> 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?
>>
> _______________________________________________
> Libraries mailing list
> Libraries at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/libraries


More information about the Libraries mailing list