liveBook · Manning

Preorder traversal

As explained in Clojure: The Essential Reference

A pre-order traversal processes a node before recursively processing its children.

Preorder traversal visits a node before descending into its children. This depth-first ordering is useful when a transformation must inspect or change a branch before nested values are processed. section 8.4 section 8.4.2

A preorder traversal has a simple contract:

  • Visit every nested item, including collections and non-collection values. section 8.4.2
  • Apply a one-argument function before entering an inner collection. section 8.4.2
  • Return a structure whose type generally follows the input, depending on transformations performed by the function. section 8.4.2
  • Accept any form, including nil, while recognizing that unusual collection implementations can raise UnsupportedOperationException. section 8.4.2

Observe the visitation order

(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 collection is visited first, followed by each nested item in depth-first order. The final value remains structurally unchanged because the function returns each item unchanged. section 8.4.1 section 8.4.2

Alter traversal before descending

Preorder processing can prevent work in a nested branch. For example, a function can recognize a node of type "pipeline" and change its contents before nested actions are reached. This differs from postorder traversal, which processes children before their parent and is better suited to combining already-processed results. section 8.4.2 section 8.4.1

Figure 8.11. Depth-first, pre-order traversal of a simple tree. The continuous line shows the traversal path, while the little cameras represent the call to the visiting function.
40 preorder traversal

The traversal diagram makes the depth-first, parent-before-children order visible. section 8.4.1

How Clojure: The Essential Reference covers it

How deep it goes
Defines depth-first ordering, function timing, inputs, outputs, and exceptions, but defers implementation internals.
Examples
Uses nested vectors, prewalk-demo output, and a pipeline branch whose descendants should not execute.
What it assumes
Assumes familiarity with Clojure functions and collections while explaining nested structures and traversal ordering.
What you can do after
Apply it via clojure.walk/prewalk to inspect or transform each nested value before descending into children.
How it connects
Connects depth-first traversal with post-order traversal, tree traversal, nested data transformation, and Clojure walk functions.

Also explained in

Compare how 2 books explain preorder traversal →

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.