liveBook · Manning

Conj

As explained in Clojure: The Essential Reference

conj is a Clojure function that adds one or more items to a collection according to the collection's type-specific conjoining semantics.

`conj` adds one or more items to a collection and returns the result. The collection comes first: `(conj coll x)` or `(conj coll x & xs)`. Where an item goes depends on the receiving collection, so `conj` does not mean “append.” section 8.2.1

The collection decides

`(conj [1 "a" :c] \x)` ⇒ `[1 "a" :c \x]` `(conj (range 3) 99)` ⇒ `(99 0 1 2)` `(conj () 1 2 3)` ⇒ `(3 2 1)` Vectors append; sequences and lists shown here add at the front. With several items, list results therefore appear in reverse argument order. section 8.2.1 section 9.4.1

Maps accept entries rather than arbitrary items. A two-element vector supplies a key and value; another map can supply several entries at once. section 8.2.1

Conjoining map entries

`(conj {:a 1} [:b 2])` ⇒ `{:a 1 :b 2}` `(conj {:a 1 :b 2} {:c 3 :d 4})` ⇒ `{:a 1, :b 2, :c 3, :d 4}` A list pair is not interchangeable with an entry vector: `(conj {} '(1 2))` throws an exception. section 8.2.1

Check the receiving collection when an addition fails or lands somewhere unexpected:

  • `nil` is treated as an empty list. Items may be `nil` where the collection accepts them; arrays and Java collections such as `java.util.ArrayList` are not supported as the receiving collection. section 8.2.1
  • Primitive-type vectors require compatible items. Sorted sets require comparable elements; sorted maps apply that requirement to keys. section 8.2.1

For a list-backed stack, `conj` acts as push, pairing with `peek` and `pop`. `into` repeatedly uses `conj`: collecting values into an empty list reverses their order, while collecting into a vector uses its append behavior. Choose the destination collection for the insertion semantics you need. section 9.4.1 section 12.2

How Clojure: The Essential Reference covers it

How deep it goes
Defines arities, return behavior, collection-specific insertion, accepted inputs, and notable restrictions through examples.
Examples
Shows vector append, sequence and list head insertion, map-entry addition, and a list-pair exception.
What it assumes
Assumes familiarity with Clojure collection literals and function calls while illustrating how insertion differs by collection type.
What you can do after
Apply it to add items with collection-appropriate semantics and recognize incompatible map entries or receiving collections.
How it connects
Connects list-backed stacks to peek and pop, and reversal to into’s repeated use of conj.

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.