[Haskell] specification of sum

Cale Gibbard cgibbard at gmail.com
Tue Nov 1 18:44:20 EST 2005

On 01/11/05, Scherrer, Chad <Chad.Scherrer at pnl.gov> wrote:
> I was wondering... In my experience, it's worked much better to use
> sum' = foldl' (+) 0
> than the built-in "sum" function, which leaks memory like crazy for
> large input lists. I'm guessing the built-in definition is
> sum = foldr (+) 0
> But as far as I know, (+) is always strict, so foldl' seems much more
> natural to me. Is there a case where the build-in definition is
> preferable?
> Chad Scherrer
> Computational Mathematics Group
> Pacific Northwest National Laboratory

You don't always want (+) to be strict. Consider working with the ring
of formal power series over, say, the integers. You don't want (+) to
force the evaluation of an infinite formal summation which is passed
to it, since that's an infinite loop, so it will have to be
non-strict, somewhat like zipWith (+) over the lists of coefficients.

 - Cale

More information about the Haskell mailing list