Created
July 26, 2013 23:27
-
-
Save tbatchelli/6092907 to your computer and use it in GitHub Desktop.
Sieve of Erastothenes as a data-flow using core.async (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)
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
(ns sieve.core | |
(:require [clojure.core.async :as async :refer :all]])) | |
(defn counter-stream [n] | |
(let [c (chan)] | |
(go | |
(loop [i n] | |
(>! c i) | |
(recur (inc i)))) | |
c)) | |
(defn filter-multiples [p in] | |
(let [out (chan)] | |
(go | |
(loop [] | |
(let [v (<! in)] | |
(when-not (zero? (mod v p)) | |
(>! out v))) | |
(recur))) | |
out)) | |
(defn sieve [] | |
(let [primes (chan)] | |
(go | |
(loop [c (counter-stream 2)] | |
(let [p (<! c)] | |
(>! primes p) | |
(recur (filter-multiples p c))))) | |
primes)) | |
(comment | |
(def primes (sieve)) | |
(<!! primes) | |
2 | |
(<!! primes) | |
3 | |
etc...) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment