Last active
September 14, 2019 02:05
-
-
Save bmaddy/7252993 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes using Clojure's core.async.
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 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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