Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
clojure/core.asyncで素数の篩(ふるい)
(ns async-test.core
(:require [clojure.core.async :as async :refer [<! >! <!! chan go]]))
(defn generate
[]
(let [ch (chan)]
(go
(doseq [e (iterate inc 2)]
(>! ch e)))
ch))
(defn sieve-filter
[in prime]
(let [out (chan)]
(go
(while true
(let [i (<! in)]
(when-not (= (mod i prime) 0)
(>! out i)))))
out))
(defn sieve
[]
(let [out (chan)]
(go
(loop [ch (generate)]
(let [prime (<! ch)]
(>! out prime)
(recur (sieve-filter ch prime)))))
out))
(defn -main
[]
(let [primes (sieve)]
(doseq [_ (range 100)]
(println (<!! primes)))))
(defproject async-test "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/core.async "0.1.0-SNAPSHOT"]]
:repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/"}
:main async-test.core)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment