Skip to content

Instantly share code, notes, and snippets.

@neolee
Created March 23, 2013 14:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neolee/5227862 to your computer and use it in GitHub Desktop.
Save neolee/5227862 to your computer and use it in GitHub Desktop.
Lazy primes generator by using a map, a Sieve of Eratosthenes modified by Christophe Grand (co-author of the great book 'Clojure Programming').
(defn primes []
(letfn [(enqueue [sieve n step]
(let [m (+ n step)]
(if (sieve m)
(recur sieve m step)
(assoc sieve m step))))
(next-sieve [sieve candidate]
(if-let [step (sieve candidate)]
(-> sieve
(dissoc candidate)
(enqueue candidate step))
(enqueue sieve candidate (+ candidate candidate))))
(next-primes [sieve candidate]
(if (sieve candidate)
(recur (next-sieve sieve candidate) (+ candidate 2))
(cons candidate
(lazy-seq (next-primes (next-sieve sieve candidate)
(+ candidate 2))))))]
(cons 2 (lazy-seq (next-primes {} 3)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment