Why will this defeat Haskell's lazy evaluation?

Today I am writing a small program in Haskell. I found that in ghci interactive mode it is:

take 100 $ foldl (\s a -> s ++ [last s + a]) [0] (1:[6,12..])

      

will 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])

      

may work fine.

Why can't Haskell lazy evaluation make the first start in memory (3G, BTW)? Or maybe it's ghci quirk?

Thanks for any inputs!

+3


source to share


1 answer


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

it will be a problem. I don't know if this is homework, but I think you want to figure out the solution yourself, so here's a hint: instead of looking for a reversal - here's an example with Fibonacci

+7


source







All Articles