Lazy List of Prime Numbers

后端 未结 4 561
清歌不尽
清歌不尽 2021-01-30 22:22

How would one implement a list of prime numbers in Haskell so that they could be retrieved lazily?

I am new to Haskell, and would like to learn about practical uses of t

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 23:00

    primes = 2 : [x | x <- [3..], all (\y -> x `mod` y /= 0) 
                       (takeWhile (<= (floor . sqrt $ fromIntegral x)) primes)]
    

    With 2 in the list initially, for each integer x greater than 2, check if for all y in primes such that y <= sqrt(x), x mod y != 0 holds, which means x has no other factors except 1 and itself.

提交回复
热议问题