liveBook · Manning

Prewalk

As explained in Clojure: The Essential Reference

prewalk is a Clojure function that applies a function to each node of a nested data structure before recursively traversing that node's children.

prewalk applies a one-argument function to every node in an arbitrarily nested data structure using depth-first, pre-order traversal. It transforms or inspects the current node before recursively descending into its children, so changing a node can alter the traversal path. section 8.4.1 section 8.4.2

Use the contract to predict inputs, outputs, and edge cases:

  • Call `(prewalk f form)` with a mandatory one-argument function and a form of any type, including nil. section 8.4.2
  • Apply `f` to collections and non-collection values alike; recursively visit collection children after transforming their parent. section 8.4.2
  • Return a structure whose type generally matches the input, although transformations performed by `f` determine the final result. section 8.4.2
  • Expect `UnsupportedOperationException` when a recognized collection type lacks required operations; `bean` is a rare standard-library example. section 8.4.2

Observe the visit order

```clojure (require '[clojure.walk :refer [prewalk]]) (prewalk #(do (println %) %) [1 [2 [3]]]) ;; [1 [2 [3]]] ;; 1 ;; [2 [3]] ;; 2 ;; [3] ;; 3 ;; [1 [2 [3]]] ``` The outer vector is visited first, followed by each nested branch. A practical use is changing a node before its descendants are processed, such as preventing execution of an entire nested branch marked as a pipeline. section 8.4.1 section 8.4.2

(require '[clojure.walk :refer [prewalk]]) ; #1

(prewalk #(do (println %) %) [1 [2 [3]]]) ; #2

;; [1 [2 [3]]] ; #3
;; 1           ; #4
;; [2 [3]]     ; #5
;; 2
;; [3]
;; 3           ; #6
;; [1 [2 [3]]] ; #7

Run the compact listing to see prewalk's callback order and unchanged return value when the callback only prints and returns each node. section 8.4.2

How Clojure: The Essential Reference covers it

How deep it goes
Defines the contract, ordering, output behavior, and collection exception while leaving implementation internals largely implicit.
Examples
Demonstrates nested vectors, printed visit order, and skipping actions beneath pipeline nodes.
What it assumes
Builds from walk's child iteration and outer reconstruction, then extends those steps into recursive traversal.
What you can do after
Apply it via clojure.walk to inspect, transform, or redirect traversal through nested data structures.
How it connects
Connects prewalk with walk, postwalk, depth-first traversal, tree traversal, and data transformation.

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.