Today I am writing a small program in Haskell. I found that in ghci’s interactive mode, this:
take 100 $ foldl (\s a -> s ++ [last s + a]) [0] (1:[6,12..])
would hang ghci and make it crash due to out of memory, but this:
take 100 $ foldl (\s a -> s ++ [last s + a]) [0] (1:[6,12..606])
could run just fine.
Why Haskell’s lazy evaluation cannot make the first one run within the memory (3G, BTW)? Or maybe it is ghci’s quirk?
Thanks for any inputs!
I think your problem is this:
foldlhas some problems with infinte lists (see HaskelWiki: Fold)But if you try to use
foldrlast swill be a problem.Don’t know if this is a homework but I think you want to find the solution yourself, so here is a hint: instead of a fold look for a unfold – here is a example with the fibonaccis