Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Haskell lazy evaluation [duplicate]

Forgive my stupid question, I'm new to Haskell.

I tried in Haskell the following:

sum [fib n| n <- [1..], (even (fib n) && fib n < 4000000)] 

which takes infinite time. If I leave out n <- [1..], the solution comes at once.

I thought it shouldn't matter because Haskell is evaluating lazy.Did I misunderstand lazy evaluation?

like image 968
Leon Backus Avatar asked Jul 15 '26 07:07

Leon Backus


1 Answers

Note that

sum [ n | n <- [1..], n < 10 ]

will not terminate as well, since it will try all possible ns just in case one more element is found to be "less than 10" so that it is included in the sum.

By comparison,

sum $ takeWhile (< 10) [ n | n <- [1..] ]

will terminate, since takeWhile will discard the rest of the list as soon as an item is found not to satisfy the predicate <10.

like image 191
chi Avatar answered Jul 17 '26 21:07

chi