[Haskell-cafe] curious about sum

Henk-Jan van Tuyl hjgtuyl at chello.nl
Wed Jun 17 07:07:41 EDT 2009

On Wed, 17 Jun 2009 10:38:23 +0200, Yitzchak Gale <gale at sefer.org> wrote:

> While there are indeed certain very rare situations in which
> you want foldr or foldl for sum, they are both joltingly wrong
> as the default for typical usage.
> In practice, I find this to be a small annoyance that occurs
> so often that it becomes a major one. Can we please fix it
> already?
> Let it be noted that this discussion also applies to product.
> Thanks,
> Yitz

I have done some research on functions in the base libraries, whether they
can handle large lists; I didn't check them all, because there are so many
of them. sum and product are certainly not the only ones having problems.
For example:
     Hugs> reverse [1 .. 999999]
     ERROR - C stack overflow

An improved reverse function:
     reverse' = foldl' (flip (:)) []
There is no need for reverse to be lazy, so this one could replace the
original one.
reverse' is not too strict:
     Data.List> let reverse' = foldl' (flip (:)) [] in head $ reverse'
[undefined, 1]

Some of the other functions that have problems with large lists are:
take    (in GHCi, not in Hugs)
drop    (in GHCi, not in Hugs)
splitAt (in GHCi, not in Hugs)

By the way, sum and product are implemented with foldl' in Hugs.

Met vriendelijke groet,
Henk-Jan van Tuyl


More information about the Haskell-Cafe mailing list