liveBook · Manning

Assoc-in

As explained in Clojure: The Essential Reference

assoc-in is a Clojure function that returns an associative collection with an association added or replaced at a nested key path.

assoc-in returns an associative collection with a value added or replaced at a nested key path. It generalizes assoc across maps and other associative structures, including vectors. section 11.3.1

Use the three-argument form:

  • (assoc-in map ks val) follows each key in ks, then associates val at the final location. section 11.3.1
  • The input collection may be nil, which defaults to an empty map; nested vector paths should contain integers. section 11.3.1
  • A missing or invalid path can raise exceptions, including IndexOutOfBoundsException, IllegalArgumentException, or ClassCastException. section 11.3.1

Replace a nested vector element

(def m {:a "1" :b "2" :c {:x1 {:x2 "z1"}}}) (assoc-in m [:c :x1 :x2] "z2") ;; {:a "1" :b "2" :c {:x1 {:x2 "z2"}}}

How Clojure: The Essential Reference covers it

How deep it goes
Explains the signature, path traversal, defaults, vector constraints, and several exception cases, with concise nested examples.
Examples
Uses nested maps and vectors to replace values at paths such as [:c :x1 :x2] and [2 :ads 1].
What it assumes
Assumes familiarity with associative collections, keys, values, maps, vectors, and Clojure function calls.
What you can do after
Apply via Clojure’s assoc-in function to add or replace values at nested paths.
How it connects
Connects assoc-in with assoc, dissoc, maps, vectors, and associative data structures.

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.