c:\>ghci
Loading package ghc-prim ... linking ... done.
Loading package integer ... linking ... done.
Loading package base ... linking ... done.
Prelude> sum [0..10^6]
*** Exception: stack overflow
Prelude>
So the easiest way to fix this is by defining a strict sum:
import Data.List (foldl')
sum' = foldl' (+) 0
Or if you prefer to see how this works internally:
sum' xs = aux 0 xs
where
aux s [] = s
aux s (x:xs) = let s' = x+s
in s' `seq` aux s' xs
An interesting thing I learned from this mailing list is that the stack overflow does not occur because the huge addition expression (0+1+2+3+4+5+6+7+...) is build up in memory, but because the evaluation of this gigantic expression *after* it has been completely build up in memory.
One can demonstrate that the addition expression is first build up in memory like this:
c:\>ghci
Loading package ghc-prim ... linking ... done.
Loading package integer ... linking ... done.
Loading package base ... linking ... done.
Prelude> sum [0..10^100]
<interactive>: out of memory