liveBook · Manning

Stateful transducer

As explained in Clojure: The Essential Reference

A stateful transducer is a transducer that retains partial processing state until it receives a signal that reduction is complete.

A stateful transducer retains partial processing state until reduction finishes. This matters when a transformation buffers or accumulates data, because receiving the final item does not necessarily flush that state. transduce signals completion by calling the reducing function with one argument, allowing the transducer chain to release buffered results consistently. section 7.2.3

Completion flushes partition-all

With (partition-all 3), two inputs remain buffered until the final reducing-function call: (xform-reductor 0 0) ; 0 (xform-reductor 0 0) ; 0 (xform-reductor 0) ; #done! 2 Without that final one-argument call, the buffered values would not be emitted and the result would remain 0. section 7.2.3

(def xform                              ; #1
  (comp (map inc)
        (partition-all 3)
        cat))

(def xform-reductor                     ; #2
  (xform
    (completing +
      #(do (print "#done! ") %))))

(xform-reductor 0 0)                    ; #3
;; 0
(xform-reductor 0 0)                    ; #4
;; 0
(xform-reductor 0)                      ; #5
;; #done! 2

Inspect the reducing function and its final one-argument completion call. section 7.2.3

How Clojure: The Essential Reference covers it

How deep it goes
Shows internal initialization, buffering, reducing, and teardown, but does not develop a general implementation beyond the partition-all example.
Examples
Uses partition-all with two zeros, an xform-reductor trace, and a final one-argument reducing-function call.
What it assumes
Assumes familiarity with reducing functions and transducer chains while demonstrating completion behavior through a concrete partition-all reduction.
What you can do after
Evaluate transducer results by recognizing when buffered state requires a final completion call.
How it connects
Connects stateful transducers to transducers, transduce, completing, reduced, reducing functions, and partition-all.

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.