我一直在思考这个问题,并觉得分享出来是个好主意。这基本上是一种向原子元素添加东西的方式,同时还要保持追踪结果是否已被还原的承诺。有点像你可以向 core.async/chan 提供一个转换器
(defn mkadder
"returns a function which, given a value, adds that value the the atom a with the reducing function rf. If the result is reduced, deliver the dereferenced result to promise p."
[a p rf]
(fn [x]
(let [result (rf a x)]
(if (reduced? result)
(do (deliver p @@result) @result) ;;what to return?
result))))
(defn acc
"accumulates state in an atom subject to a transducer. returns a map
with the keys :adder, :a and :p. Use the :add! function to add
state. :p is a promise which will be delivered the state in a when
rf is realized"
([xf rf] (acc xf rf (rf)))
([xf rf init]
(let [a (atom init)
swapper (fn [acc x] (doto acc (swap! rf x)))
rf (xf swapper)
p (promise)]
{:add! (mkadder a p rf) :a a :p p})))
;;demo
(let [{:keys [add! a p]}
(acc (comp (map inc) (filter even?) (take 5)) conj)]
(future
(doseq [i (range 20)]
(add! i)
(println "atom contains: " @a "promise realized?" (realized? p))
(Thread/sleep 500))))
我有一个场景,其中有来自外部来源的一系列消息需要经过 filter 和 take/take-while 处理,如果能直接利用 clojure.core 中的这些功能而不是自己管理状态就很好了。并且 core.async 会有些过度(我不需要 CSP)。