I tried the list comprehension [2^i | i<-[1..], 2^i<34]
, but I got something strange from GHCi :
Prelude> [2^i | i<-[1..], 2^i<34]
[2,4,8,16,32
Then I tried filter (<34) [2^i | i<-[1..] ]
, and I get the same result .
My original purpose is to use this in something like while
loop , where we don't know when to stop the loop .
CodePudding user response:
Haskell doesn't know that 2^i >= 34
is implied by i > C
for some value C
. It will keep trying every value in the (infinite) iterator to see if there are any more values that meet the condition.
You can help Haskell out by using takeWhile
on an infinite list instead of using a guard to filter the infinite list.
> takeWhile (< 34) [2^i | i <- [1..]]
[2,4,8,16,32]