Skip to content

Instantly share code, notes, and snippets.

@msassak
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msassak/9286191 to your computer and use it in GitHub Desktop.
Save msassak/9286191 to your computer and use it in GitHub Desktop.
core.async demo
(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