public
Last active

Sieve of Erastothenes as a data-flow using core.async (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)

  • Download Gist
core.clj
Clojure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
(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...)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.