liveBook · Manning

Append!

As explained in Clojure: The Essential Reference

r/append! is a Clojure reducer function that adds an element to a mutable Java collection and returns the collection result.

r/append! is a two-argument reducing function in clojure.core.reducers. It adds an element to a mutable java.util.Collection through the Java .add method and returns the collection result. Its practical role is building mutable accumulators during fold operations instead of repeatedly creating temporary persistent data structures. section 7.1.4 section 7.1

Use r/append! when:

  • The accumulator is a subtype of java.util.Collection. section 7.1.4
  • A fold should incrementally populate mutable collections while r/cat combines fold results into a Cat structure. section 7.1.4
  • A custom collection should receive the elements: provide its constructor to r/cat, then use r/append! as the reducing function. section 7.1.4

Appending into a fold result

(require '[clojure.core.reducers :as r]) (def input (r/map inc (into [] (range 1000)))) (take 5 (r/fold r/cat r/append! input)) ;; (1 2 3 4 5) (take 5 (r/foldcat input)) ;; (1 2 3 4 5) Both forms use the same mutable-accumulator strategy; r/foldcat packages the r/cat and r/append! combination. section 7.1.4

Choosing a collection type

(import '[java.util HashSet]) (def words (r/fold (r/cat #(HashSet.)) r/append! (r-word text))) (count words) ;; 185561 Here, r/append! inserts each reduced element into HashSet accumulators rather than constructing persistent collections for every fold chunk. section 7.1.4

How Clojure: The Essential Reference covers it

How deep it goes
Defines the two-argument contract and Java .add behavior, then demonstrates collection selection and fold composition.
Examples
Demonstrates ArrayList accumulation, HashSet accumulation, and equivalent foldcat usage over transformed input.
What it assumes
Assumes familiarity with reducing functions, reducible collections, and fold operations.
What you can do after
Apply it via clojure.core.reducers to populate mutable Java collections during folds.
How it connects
Connects reducing functions, fold, foldcat, cat, mutable collections, and persistent data-structure allocation.

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.