Skip to content

Instantly share code, notes, and snippets.

@tbatchelli
Created July 26, 2013 23:27
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbatchelli/6092907 to your computer and use it in GitHub Desktop.
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)
(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