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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With