A short prime sieve

31 Oct 2015

I’m currently in the process of job hunting, so to de-stress, I’ve been playing with Haskell a lot. Here’s a very short function to generate lists of prime numbers.

-- generate a list of prime numbers less than or equal to n
import Data.List
primeList :: Integral a => a -> [a]
primeList n = nubBy (\x y-> x`mod`y==0) [2..n]

If instead, you want a list containing n primes:

-- generate a list of n prime numbers
import Data.List
listPrimes :: Integral a => a -> [a]
listPrimes n = take n $ nubBy (\x y-> x`mod`y==0) [2..]

The next project will possibly be something slightly more practical.


edited to fix a minor issue with second version