In Haskell, what's the difference between using takeWhile or using a “regular” inequality in this list comprehension?

后端 未结 1 1212
天命终不由人
天命终不由人 2020-12-31 09:32

I\'m trying to learn me a Haskell (for great good), and one of the many different things I\'m doing is trying to tackle some Project Euler problems as I\'m going along to te

相关标签:
1条回答
  • 2020-12-31 09:42

    The function takeWhile keeps taking elements of the input list until it reaches the first element that doesn't satisfy the predicate, and then it stops. As long as there is at least one element that doesn't satisfy the predicate, takeWhile turns infinite lists into finite lists.

    Your first expression says

    Keep taking elements of this infinite list until you find one greater than 4,000,000 and then stop. Include each element in the output if it's even.

    The second expression says

    Keep taking elements of this infinite list. Include each element in the output if it's less than or equal 4,000,000 and it's even.

    When you observe an output that hangs forever, the function is busily generating more fibonacci numbers and checking to see if they're less than or equal 4,000,000. None of them are, which is why nothing is printed to the screen, but the function has no way of knowing that it's not going to encounter a small number a bit further down the list, so it has to keep checking.

    0 讨论(0)
提交回复
热议问题