Created
March 23, 2013 14:15
-
-
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').
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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