reduce

added

ns
clojure.core.async

type
function

(reduce f init ch)

f should be a function of 2 arguments. Returns a channel containing
the single result of applying f to init and the first item from the
channel, then applying f to that result and the 2nd item, etc. If
the channel closes without yielding items, returns init and f is not
called. ch must close before reduce produces a result.

                (require '[clojure.core.async :as async])

;; some expensive io call
(defn expensive-call [m] 
  (Thread/sleep 2000) m)

(->> [{:a 1} {:b 2} {:c 3} {:d 4}]
     (map (fn [m] 
            (async/thread 
               (expensive-call m)))) ; creates a thread per call
     (async/merge)                   ; merges the 4 chans returned into 1
     (async/reduce merge {})         ; reduces items in chan with merge
     (async/<!!))
;;=> {:a 1, :c 3, :b 2, :d 4}
            
                (require '[clojure.core.async :as async])

(def c 
  (async/to-chan (range 10)))

(async/<!! (async/reduce + 0 c))
;;=> 45