0
votes

I'm new to Haskell. Following list comprehension dose not work good. ghci stop it's output. (after type '7', ghci stop long long time.)

Prelude Data.Numbers.Primes> [x | x <- primes, x <= 10]
Loading package array-0.4.0.1 ... linking ... done.
Loading package deepseq-1.3.0.1 ... linking ... done.
Loading package old-locale-1.0.0.5 ... linking ... done.
Loading package time-1.4.0.1 ... linking ... done.
Loading package random-1.0.1.1 ... linking ... done.
Loading package Numbers-0.2.1 ... linking ... done.
[2,3,5,7^Z
[2]+  Stopped                 ghci

Why ghci stop its working and how can I fix it? Thank you.

2
Could we see your main code(the "primes" function and others)?Steven Dobay
@StevenDobay Data.Numbers.Primes is from the primes package, not his code.Carl
@StevenDobay Yes. "primes" is not my code. Thank you.shaegis
@Wes I read "Generati~" but I can't fix why ghci can't work. Maybe I'm new to Haskell, so I can't understand that code. Sorry.shaegis
@shaegis yeah sorry it isn't an exact duplicate, that was my mistakeWes

2 Answers

5
votes

Assuming primes contains all primes (and therefore it is an infinite list), the list comprehension won't terminated if you try to evaluate the list past the value 7. Since

[x | x <- primes, x <= 10]

is essentially the same as

filter (<= 10) primes

you would filter all primes whether they are lesser or equal to ten. However, you know that the primes are ordered, so you can take primes, as long as they are lesser than ten:

takeWhile (<= 10) primes
2
votes

The problem is that GHCi can't know that your list of primes is ordered. Maybe after 1000000000000000 elements of primes, there comes some element that is smaller than 10, so it must be still included in the ouput? That's why ghci only prints the first elements of the result ([2,3,4,7), but not the whole result. If you only want those, you can use takeWhile, which stops after it encounters a number that doesn't match the predicate:

> takeWhile (<= 10) primes
[2,3,5,7] -- takeWhile stops after it encounters 7, because the predicate becomes false

> filter (<= 10) primes
[2,3,5,7  -- filter cannot stop, because there might still be a number later in the list that satisfies the predicate. This is what the list comprehension does.