Skip to content

Instantly share code, notes, and snippets.

@kazu-yamamoto
Created January 31, 2011 05:30
Show Gist options
  • Save kazu-yamamoto/803680 to your computer and use it in GitHub Desktop.
Save kazu-yamamoto/803680 to your computer and use it in GitHub Desktop.
import Data.Map
import Prelude hiding (lookup)
primes :: [Integer]
primes = sieve [2..]
sieve :: [Integer] -> [Integer]
sieve xs = sieve' xs empty
sieve' :: [Integer] -> Map Integer [Integer] -> [Integer]
sieve' (x:xs) table = case lookup x table of
Nothing -> x : sieve' xs (insert (x*x) [x] table)
Just facts -> sieve' xs (foldl reinsert (delete x table) facts)
where
reinsert tbl prime = insertWith (++) (x+prime) [prime] tbl
sieve' _ _ = error "sieve'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment