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?
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.
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