Your problem isn't directly takeWhile
, but rather the list comprehension.
[x | x <- primes, n `mod` x == 0]
For n = 24
, we get 24 `mod` 2 == 0
and 24 `mod` 3 == 0
, so the value of this list comprehension starts with 2 : 3 : ...
. But consider the ...
part.
The list comprehension has to keep pulling values from primes
and checking 24 `mod` x == 0
. Since there are no more prime factors of 24
nothing will ever pass that test and get emitted as the third value of the list comprehension. But since there's always another prime to test, it will never stop and conclude that the remaining tail of the list is empty.
Because this is lazily evaluated, if you only ever ask for the first two elements of this list then you're fine. But if your program ever needs the third one (or even just to know whether or not there is a third element), then the list comprehension will just spin forever trying to come up with one.
takeWhile (< 24)
keeps pulling elements from its argument until it finds one that is not < 24
. 2
and 3
both pass that test, so takeWhile (< 24)
does need to know what the third element of the list comprehension is.
But it's not really a problem with takeWhile
; the problem is that you've written a list comprehension to find all of the prime factors (and nothing else), and then trying to use a filter on the results of that to cut off the infinite exploration of all the higher primes that can't possibly be factors. That doesn't really make sense if you stop to think about it; by definition anything that isn't a prime factor can't be an element of that list, so you can't filter out the non-factors larger than n
from that list. Instead you need to filter the input to that list comprehension so that it doesn't try to explore an infinite space, as @n.m's answer shows.
[x | x <- primes, 10 `mod` x == 0]
is not[2,5]
, but something like2:5:infiniteLoop
, because after5
infinitely many primesx
will be tried since they might pass the test. Of course we know they won't, but the list comprehension does not know that. ThentakeWhile
gets stuck in the loop. – WanettawanfriedtakeWhile
would stop evaluating the infinite list when the predicate does not hold anymore. – WitcherytakeWhile
would have no problems. TrytakeWhile (<=10) [1..]
andtakeWhile (<=10) (1:2:5:let f n = f (n+1) in f 3)
. Here[1..]
is an infinite list, while1:2:5:...
is not -- it is a list with an undefined spine after its 3rd element. In an infinite list,take n list
will always return, instead when the spine is undefined it will not. – Wanettawanfried