Why can I not express the limit of infinite list in terms of filter condition in list comprehension?

Viewed 73

In my Haskell program, I want to have an expression, in essence, equivalent to the following

cList = [i | i <- [1 .. ], i <= 5]

but it seems that the evaluation of cList will not terminate, producing

[1, 2, 3, 5

in ghci session, but never return, and the CPU of my computer kept running.

but the following equivalent will terminate as expected:

bList = takeWhile (<= 5) [1 ..]

What's wrong with the expression cList as infinite list compression with a filter condition? ?

1 Answers

How do you know there are no numbers less than 5 that come after 5? List comprehensions can't know that: they're not specialized to numbers. So it keeps searching forever, because there might be more values out there. If you know it will never succeed, you have to say so, by using a different tool.

Related