liveBook · Manning

Associative container

As explained in Clojure: The Essential Reference

An associative data structure is a collection that supports lookup of values by keys or numeric indexes.

An associative container supports access by key or numeric index. In Clojure, maps use keys and vectors use indexes; records are associative too. Sets do not implement the Associative interface, although some lookup functions support them. section 8.2.3 section 11.3.2

Use contains? to ask whether a lookup position exists—not whether a collection contains a particular value. It tests keys in maps, members in sets, and valid indexes in vectors. Thus (contains? [:a :b :c] 1) is true, while (contains? [:a :b :c] :a) is false. It does not work on every collection: queues and Java ArrayLists, for example, raise an exception. section 8.2.3

The same keyed structure supports several practical operations:

  • select-keys extracts specified entries into a map: (select-keys {:a 1 :b 2} [:a]) returns {:a 1}. Given a vector, its result is still a map keyed by indexes. section 11.2.3
  • get-in follows a sequence of keys through nested data: (get-in {:a {:b 3}} [:a :b]) returns 3. Supply a not-found value when a missing path must be distinguishable from nil. section 11.2.3
  • update and update-in return a new structure after applying a function to an existing value. For example, (update-in {:a {:b 2}} [:a :b] inc) returns {:a {:b 3}}. section 11.3.2

Check presence, not truthiness

For {:a 1 :b nil}, (get m :b) yields nil even though :b exists. (contains? m :b) returns true. Use the presence test when nil is a legitimate stored value. section 8.2.3

A missing map key passed to update is created using the result of calling its function with nil; (fnil inc 0) makes this useful for counters. Vector indexes have different limits: updating at the end can append, but an index farther beyond it raises an exception. The key must be an integer. section 11.3.2

How Clojure: The Essential Reference covers it

How deep it goes
Specifies supported inputs, return behavior, missing-key cases, and exceptions through examples, without developing container internals.
Examples
Uses map-key and vector-index checks, nested lookups, word counters, and inventory updates.
What it assumes
Assumes familiarity with Clojure maps, vectors, keys, and functions; defines the relevant lookup and update contracts.
What you can do after
Apply it via Clojure's contains?, get-in, select-keys, update, and update-in to test, read, and transform keyed data.
How it connects
Connects maps, vectors, records, and sets to contains?, select-keys, get-in, update, and update-in.

Also explained in

Compare how 2 books explain associative container →

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.