
mukesh tiwari
It seems like the sum function is causing the stack overflow[1]. Graham Gill
writes: I think the problem is with laziness in the accumulator of "sum". The prelude "sum" is defined as
`Real World Haskell' actually has a warning regarding the use of
Prelude's foldl, the space leaks in causes and how to force evaluation
using `seq' in Chapter 4 under the headings `Left Folds, Laziness, and
Space Leaks' and `Avoiding Space Leaks with seq'. It just slipped my
mind, and I had the wrong assumption of the `sum' function.
mukesh tiwari
import Data.List sum' = foldl' (+) 0
An explicit version:
sum' l = sum'' l 0
where
sum'' [] a = a
sum'' (x:xs) a = let intermediate = a + x
in intermediate `seq` sum'' xs intermediate
Graham Gill
mysum xs = sum' xs 0 where sum' [] a = a sum' (x:xs) !a = sum' xs (x + a)
http://www.haskell.org/haskellwiki/Memory_leak http://www.haskell.org/haskellwiki/Performance/Strictness Anyway I just wanted to thank you for helping me solve my problem, for
All three versions work. foldl' uses `seq' to force evaluation and therefore strictness and the `BangPatterns' are a nice syntactic feature to express strictness, because the excessive use of `seq' can make code unwieldy. At least that is as far as my not fully correct understanding goes for now. the helpful links and slightly improving my understanding of Haskell's laziness. Long way to go. -- Axel Wegen