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

Viktor Dukhovni ietf-dane at dukhovni.org
Thu Dec 24 01:41:03 UTC 2020


On Wed, Dec 23, 2020 at 07:19:37PM -0600, chessai wrote:

> On mobile, but I don't see how you're compiling? Is it at least with -O1?
> 
> On Wed, Dec 23, 2020, 18:26 Keith <keith.wygant at gmail.com> wrote:
> 
> > There's no benefit to optimizing default Foldable methods for data types
> > that already have specialized methods.
> >
> > foldMap' does not care about the nesting of the structure like foldl', so
> > it's a better default choice.
> >
> > What I worry more about is that getSum . foldl' (\ z x -> z <> Sum x)
> > mempty is compiling to different code than foldl' (+) 0.

Well, perhaps the same sort of "lifting" concerns that motivated:

    getSum #. foldMap' Sum

in the default definition.  With (#.) just ignoring the `getSum` and
pretending that foldMap' already returns the correct result.  FWIW,
my builds were with "-O2".

-- 
    Viktor.


More information about the Libraries mailing list