zw324
zw324

Reputation: 27180

Why would this defeat Haskell's lazy evaluation?

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!

Upvotes: 3

Views: 255

Answers (1)

Random Dev
Random Dev

Reputation: 52270

I think your problem is this:

foldl has some problems with infinte lists (see HaskelWiki: Fold)

But if you try to use foldr last s will 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

Upvotes: 7

Related Questions