liveBook · Manning

Cat

As explained in Clojure: The Essential Reference

cat is a Clojure transducer that removes one layer of sequential wrapping by feeding the elements of each inner sequential result into a reducing function.

`clojure.core/cat` removes one layer of sequential wrapping in a transducer pipeline. It is useful when an earlier step produces a sequence for each input and the next step should receive that sequence’s elements individually. section 7.2.4

The essential contract is:

  • `cat` is used directly as a transducer; it does not need a mapping function. section 7.2.4
  • Its input at each step must be sequential. When applied to a reducing function, it feeds that function the elements of each inner sequence. section 7.2.4
  • The reducing function must support zero-, one-, and two-argument calls, as required by the transducer contract. section 7.2.4

Feeding an inner sequence to a reducer

`((cat +) 0 (range 10))` returns `45`, just as `(reduce + 0 (range 10))` does. In a pipeline, the surrounding transducer-aware operation handles the outer iteration while `cat` handles each inner sequence. section 7.2.4

(eduction
  (map range)
  (partition-all 2)
  cat
  cat               ; #1
  (range 5))

;; (0 0 1 0 1 2 0 1 2 3)

Here, `(map range)` produces inner sequences, and `(partition-all 2)` wraps them again. Two successive uses of `cat` remove those two layers, yielding `(0 0 1 0 1 2 0 1 2 3)`. section 7.2.4

Use `mapcat` when flattening also requires a transformation; use `cat` when the sequences are already present. Do not confuse `clojure.core/cat` with `clojure.core.reducers/cat` (`r/cat`), which combines results during a fold. section 7.2.4 section 7.1.4

How Clojure: The Essential Reference covers it

How deep it goes
Defines the reducing-function contract and works through flattening examples, without detailing implementation internals.
Examples
Demonstrates summing a range, unwrapping twice-nested results, and replacing mapcat with identity.
What it assumes
Assumes familiarity with reducing functions and transducer chains, while illustrating cat through a comparison with reduce.
What you can do after
Apply it via Clojure’s sequence or eduction to remove sequential wrapping without adding a mapping step.
How it connects
Relates cat to reduce, mapcat, eduction, sequence, and the distinct clojure.core.reducers/cat.

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.