[Haskell-cafe] definition of sum

Daniel Fischer daniel.is.fischer at web.de
Thu Mar 11 10:12:43 EST 2010

Am Donnerstag 11 März 2010 15:23:32 schrieb Yitzchak Gale:
> 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.

Yes. And I'd expect foldr (+) 0 to be much more useful for lazy Num 
instances than foldl (+) 0. Nevertheless, one has to take that possibility 
into account.

> > 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.

I'm not sure whether it's a wart or a bug, but I agree that it would be 
better to have the default sum strict (and provide lazysum for the cases 
where it's useful).

> Regards,
> Yitz


More information about the Haskell-Cafe mailing list