Why this happens?

David Brown haskell at davidb.org
Tue Apr 19 12:25:09 EDT 2005

On Tue, 19 Apr 2005 16:37:13 +0200, Santoemma Enrico  
<Enrico.Santoemma at beta80group.it> wrote:

> I've always thought that compilers for functional languages were able to  
> recognize tail recursion and to transform it into a loop.
> So, why this line eats all my machine's memory (and then runs out of  
> stack space)?
> sum [1..10000000]  -- ten millions

The definition of 'sum' in the standard library is too lazy.  Try:

mysum l = sum' l 0
       sum' []     a = a
       sum' (x:xs) a = let s = a+x in s `seq` sum' xs s

Perhaps someone with a better understanding can explain why the 'sum' in  
the library is defined the way it is (the standard defines it based on  
foldl, which is also lazy).  Is there a valid program that can demonstrate  
a difference between 'mysum' and the library's 'sum' function?


More information about the Glasgow-haskell-users mailing list