Reputation: 2563
I want to write a simple list comprehension in Haskell which consists of a list of infinite primes.
My attempt:
isPrime 1 = False
isPrime x = and [x `mod` z /= 0 | z <- [1..x-1]]
primes = [x | x <-[1..], isPrime x ]
But when I try running this on console as take 10 primes
it gets stuck! What is the issue?
Upvotes: 0
Views: 641
Reputation: 1369
The issue is in your isPrime function:
isPrime x = and [x `mod` z /= 0 | z <- [1..x-1]]
You take each element from 1 to x-1, and check if the remainder is not equal to zero. If any values are equal to zero, then isPrime will return false.
However, you start your list comprehension at one, which every number is divisible by.
So, we just need to start at two instead.
isPrime x = and [x `mod` z /= 0 | z <- [2..x-1]]
Now it works as expected.
λ> take 10 primes
[2,3,5,7,11,13,17,19,23,29]
If you get a problem in a larger function, try breaking it down and running each individual part to ensure the results are as you expect. In this case, isPrime 2 == False
hints to where the problem is.
Upvotes: 4