Lazy List of Prime Numbers

Mantas Vidutis picture Mantas Vidutis · Aug 29, 2010 · Viewed 26.2k times · Source

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 the lazy evaluation functionality.

Answer

Niki picture Niki · Aug 29, 2010

Here's a short Haskell function that enumerates primes from Literate Programs:

primes :: [Integer]
primes = sieve [2..]
  where
    sieve (p:xs) = p : sieve [x|x <- xs, x `mod` p > 0]

Apparently, this is not the Sieve of Eratosthenes (thanks, Landei). I think it's still an instructive example that shows you can write very elegant, short code in Haskell and that shows how the choice of the wrong data structure can badly hurt efficiency.