问题
I'm new to Haskell and playing around trying to understand a few things. If I do the following I receive a problem:
list1 = [1..]
list2 = [x | x <- list1, x <= 4]
print list2
which returns [1,2,3,4
. There isn't an end bracket on it, so it is as if the list is loading or frozen. Here is how it looks:
Prelude> print list2
[1,2,3,4
What is going on here?
回答1:
You know that the list is monotonically increasing, but Haskell does not. Use takeWhile
, instead of a list comprehension, so that list1
can stop being evaluated once you find a value greater than 4.
> list1 = [1..]
> list2 = takeWhile (<= 4) list1
> print list2
[1,2,3,4]
回答2:
What happens is that list1
is still being computed, and for each new element of the list1
predicate x <= 4
is applied, which is false
for every x
after 4
.
So, in summary:
To printout list2
interpreter need to compute list1
and check each list item that it is <= 4
, and because list1
is infinite computation of it must take infinite time.
回答3:
You are taking every element in list1
and, for each one that's less than 4, making it a entry in list2
. Look how many elements you have in list1
.
来源:https://stackoverflow.com/questions/42417446/haskell-list-frozen