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
