Skip to content

Instantly share code, notes, and snippets.

@bmaddy
Last active September 14, 2019 02:05
Show Gist options
  • Save bmaddy/7252993 to your computer and use it in GitHub Desktop.
Save bmaddy/7252993 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes using Clojure's core.async.
(ns async-sieve.core
(:require [clojure.core.async :refer [chan go go-loop <! <!! >! filter<]]))
;; Sieve of Eratosthenes as described here:
;; http://swtch.com/~rsc/thread/
;; Just to clarify, this isn't how core.async should be used, it's just a fun example:
;; "note that async channels are not intended for fine-grained computational parallelism"
;; - Rich Hickey (from http://clojure.com/blog/2013/06/28/clojure-core-async-channels.html)
(defn prime-filter [in primes]
(go
(let [prime (<! in)
out (filter< #(not= (mod % prime) 0) in)]
(>! primes prime)
(prime-filter out primes))))
(def sieve
(let [in (chan)
out (chan)]
(prime-filter in out)
(go-loop [n 2]
(>! in n)
(recur (inc n)))
out))
(def primes (repeatedly #(<!! sieve)))
(take 20 primes)
@bmaddy
Copy link
Author

bmaddy commented Sep 14, 2019

A few years after I wrote this, someone came up with a more advanced version here:
https://github.com/clojure/core.async/wiki/Sieve-of-Eratosthenes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment