如何用换能器创建另一个通道?

时间:2015-07-08 07:29:12

标签: clojure core.async transducer

我想从另一个频道中创建一个clojure.core.async频道,只过滤特定的消息。因此我找到了一个名为filter<。

的函数
=> (def c1 (chan))
=> (def c2 (filter< even? c1))
=> (put! c1 1)
=> (put! c1 2)
=> (<!! c2)
2

但该功能及其朋友被标记为已弃用:

  

不推荐使用 - 此功能将被删除。改用传感器

有一些方法可以使用带有chan传感器的频道和xform参数。如何使用传感器从现有通道构建新通道?

1 个答案:

答案 0 :(得分:6)

我对此进行了一些研究,发现了几篇有趣的文章(firstsecond),然后使用pipeline

进行了一些工作
(require '[clojure.core.async :as async :refer [chan <!! pipeline put!]])
(def c1 (chan))
(def c2 (chan))

(pipeline 4 c2 (filter even?) c1)

(put! c1 1)
(put! c1 2)
(<!! c2)
;;=> 2

我链接的第二篇文章使得管道函数周围的一些辅助函数更加清晰:

(defn ncpus []
  (.availableProcessors (Runtime/getRuntime)))

(defn parallelism []
  (+ (ncpus) 1))

(defn add-transducer
  [in xf]
  (let [out (chan (buffer 16))]
    (pipeline (parallelism) out xf in)
    out))

然后你可以简单地将频道与

联系在一起
(def c1 (chan))
(def c2 (add-transducer c1 (filter even?))

为了完成答案,你发现自己可以以类似的方式使用管道:

(defn pipe-trans
  [ci xf]
  (let [co (chan 1 xf)]
    (pipe ci co)
    co))
(def c1 (chan))
(def c2 (pipe-trans c1 (filter even?)))