5
votes

Typing following into GHCI on Windows:

foldl (+) 0 $ take 100000000 $ map sqrt [1..]

gives:

<interactive>: out of memory

while compiling (with GHC) and running this program:

main = do
    let score = foldl (+) 0 $ take 100000000 $ map sqrt [1..]
    putStrLn $ show score

prints expected answer without memory error.

Is there a reason for this behavior ? It seems to me like laziness of Haskell should prevent this one liner from crashing.

1
The problem is actually too much laziness.hammar

1 Answers

15
votes

It's just GHC doing strictness and other optimizations. GHCi doesn't do the same sort of optimizations that the full compiler does.

In particular that foldl is building up way too many thunks and those are causing your overflow. However when I change this to the strict foldl' even GHCi can handle it. You should read this question to learn a bit more about why this is.