Last active
August 29, 2015 13:56
-
-
Save msassak/9286191 to your computer and use it in GitHub Desktop.
core.async demo
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 demo | |
(:require [clojure.core.async :as a :refer [go | |
go-loop | |
chan | |
>! | |
<! | |
close]])) | |
(defn int-producer | |
"Return a channel containing the integers from 0 to n. | |
n defaults to 20." | |
([] | |
(int-producer 20)) | |
([n] | |
(let [ch (chan 5)] | |
(go-loop [i 0] | |
(>! ch i) | |
(if-not (= i n) | |
(recur (inc i)) | |
(close! ch))) | |
ch))) | |
(defn apply-ch | |
"Apply values taken from ch to fn0." | |
[ch fn0] | |
(go-loop [v (<! ch)] | |
(when-not (nil? v) | |
(fn0 v) | |
(recur (<! ch))))) | |
(defn printing-consumer | |
"Print values from ch until it closes." | |
[ch] | |
(apply-ch ch println)) | |
(defn multmap | |
"Given a channel ch, returns a vector of two channels, | |
the first containing the results taken from ch, the second | |
the results of applying fn0 to the results taken from ch." | |
[ch fn0] | |
(let [m (a/mult ch)] | |
[(a/tap m (chan)) (a/map< fn0 (a/tap m (chan)))])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment