File: ex-altsgo.clj

package info (click to toggle)
core-async-clojure 1.5.648-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 624 kB
  • sloc: xml: 77; sh: 41; makefile: 24
file content (25 lines) | stat: -rw-r--r-- 606 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
(require '[clojure.core.async :as async :refer [<! >! timeout chan alt! alts! go]])

(defn fan-in [ins]
  (let [c (chan)]
    (go (while true
          (let [[x] (alts! ins)]
            (>! c x))))
    c))

(defn fan-out [in cs-or-n]
  (let [cs (if (number? cs-or-n)
             (repeatedly cs-or-n chan)
             cs-or-n)]
    (go (while true
          (let [x (<! in)
                outs (map #(vector % x) cs)]
            (alts! outs))))
    cs))

(let [cout (chan)
      cin (fan-in (fan-out cout (repeatedly 3 chan)))]
  (go (dotimes [n 10]
        (>! cout n)
        (prn (<! cin))))
  nil)