[Haskell-cafe] definition of sum

Yitzchak Gale gale at sefer.org
Thu Mar 11 09:23:32 EST 2010

TeXitoi wrote:
>> why is foldl used by Data.List for sum?

Daniel Fischer wrote:
> Because Haskell is a non-strict language, and foldl' is strict -- someone
> might write a (legitimate) Num instance for a datatype such that
> foldl (+) 0 xs returns a good value, but foldl' (+) 0 xs gives
> ***Exception: Prelude.undefined for some lists xs.

It is possible to define such a Num instance, but it is extremely rare
for anything like that to come up in practice.

> However, with optimisations turned on... GHC knows that sum is
> actually strict

GHC does that when optimizations are turned on, but that behavior
is not required by the Haskell standard. So there is no guarantee
that any given compiler will produce usable output if you use foldl
instead of foldl' for sum.

In GHCi sum is broken, because optimizations are not in
effect there. You have to define your own version of sum
using foldl' for every GHCi session (or put it in your .ghci file).

So it's a trade-off between a slight convenience in a bizarre
corner case and general usability. I agree with Don that this is
a bug in the Haskell 98 standard.


More information about the Haskell-Cafe mailing list