reduce-kv reduces an associative data structure while preserving access to each key and value. Its reducing function receives the accumulator, key, and value, then returns the next accumulator. section 11.3.4
Call it as (reduce-kv f init coll). The initial value reaches f first; subsequent calls receive each prior result until the collection is exhausted. nil returns init. section 11.3.4
Update every map value
(reduce-kv (fn [m k v] (assoc m k (inc v))) {} {:a 1 :b 2 :c 3}) ;; {:a 2, :b 3, :c 4} section 11.3.4
Transform environment-variable keys
(reduce-kv (fn [m k v] (assoc m (transform k) v)) {} env) ;; {:term-program "iTerm.app", :shell "/bin/bash", :command-mode "Unix2003"} section 11.3.4
Keep these boundaries in mind:
- Supports types implementing IKVReduce or IPersistentMap, including maps and vectors; unsupported types such as lists throw IllegalArgumentException. section 11.3.4
- Java maps are not supported by default, but an IKVReduce implementation can extend reduce-kv to map-like types. section 11.3.4
- A reducing function may return reduced to stop early; custom protocol implementations must detect and dereference that value. section 11.3.4
(reduce ; #1
(fn [m [k v]] (assoc m k (inc v)))
{}
{:a 1 :b 2 :c 3})
;; {:a 2, :b 3, :c 4}
(reduce-kv ; #2
(fn [m k v] (assoc m k (inc v)))
{}
{:a 1 :b 2 :c 3})
;; {:a 2, :b 3, :c 4}
Compare ordinary reduce, which destructures key-value pairs, with reduce-kv, which receives the key and value as separate arguments. section 11.3.4
