liveBook · Manning

Reduce-kv

As explained in Clojure: The Essential Reference

reduce-kv is a Clojure function that reduces an associative data structure by applying a three-argument function to an accumulator, key, and value for each entry.

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

How Clojure: The Essential Reference covers it

How deep it goes
Defines arguments, return behavior, supported protocols, exceptions, custom extensions, and early termination.
Examples
Demonstrates value updates, environment-key transformation, Java-map extension, and early termination.
What it assumes
Assumes familiarity with Clojure functions, reducers, associative collections, and protocol-based dispatch.
What you can do after
Apply reduce-kv to transform associative data while retaining each entry’s key and value.
How it connects
Connects reduce-kv with reduce, IKVReduce, IPersistentMap, associative collections, and reducers/fold.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.