Basket Making 101

Praxis 2: Write a function that calculates the list of prime numbers using the Sieve of Eratosthenes.

Ummm, yeah. Done it a couple dozen times before over at Project Euler. Never hurts to review. I did manage to use more function composition this time around. Oh, and don’t forget to install module data.ordlist using Cabal.

import Data.List.Ordered

primes :: Integer -> [Integer]
primes m = 2 : sieve [3,5..m]
        sieve [] = []
        sieve (p:xs) = p : sieve (minus xs [p*p, p*p+2*p..m])

main = do
    putStrLn "Enter n: "  
    input <- getLine
    putStrLn $ "# of primes: " ++ (show . length . primes $ read input)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s