Lazy List of Prime Numbers

后端 未结 4 627
清歌不尽
清歌不尽 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:25

    There are a number of solutions for lazy generation of prime sequences right in the haskell wiki. The first and simplest is the Postponed Turner sieve: (old revision ... NB)

    primes :: [Integer]
    primes = 2: 3: sieve (tail primes) [5,7..]
     where 
      sieve (p:ps) xs = h ++ sieve ps [x | x <- t, x `rem` p /= 0]  
                                    -- or:  filter ((/=0).(`rem`p)) t
                      where (h,~(_:t)) = span (< p*p) xs
    

提交回复
热议问题