[Haskell-beginners] Prime numbers -- specific list comprehension explained

Alexander Chen alexander at chenjia.nl
Wed Jan 15 14:41:00 UTC 2020


Hi,

This could gives you for any given integer the list of prime numbers. source is from a stack overflow snippet.

helper function:
isqrt :: Integral a => a -> a
isqrt = floor . sqrt . fromIntegral

main function:
primes 1 = []
primes n = 2:[i | i <- [3,5..n], and [mod i k /= 0 | k <- primes (isqrt i)]]

my main unclarity is how I should interpret i and k in de mod part. At every step of the recursion.

example: primes 10.

it should generate [2,3,5,7,9] if you ignore the second part.

however, when I look at the second part

then first I need to do this primes (isqrt 10), which give primes 3. which gives met [2,3]. 
first question) I haven't reached base case in this situations so can i or can i not meaningfully evaluate mod i k /= 0?
Independent of that I now go deeper to reach base case.
So I go to primes (isqrt 3) which gives me primes 1 which is []. Now I hit the base case and need to definitely evaluate mod i k /= 0.
second question) but in this case what is i and what is k?

If I have it completely wrong, then please be patience. I appreciate the input!

best,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20200115/14f014e5/attachment.html>


More information about the Beginners mailing list