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

坚强是说给别人听的谎言 提交于 2019-11-30 11:51:11

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!