liveBook · Manning

Zipper

As explained in Clojure: The Essential Reference

A zipper is a data structure that represents a focused location in a recursively nested structure together with the context needed to navigate and update it.

A zipper keeps a focused location in a tree so you can navigate and edit nested data without mutating the original. In `clojure.zip`, a location is not the node itself: `zip/node` returns data, while movement functions return new locations. Call `zip/root` to obtain the tree with your changes; create a new zipper to navigate it again. section 8.4.4

Choose the operations that fit the job:

  • Create a location with `zip/vector-zip`, `zip/seq-zip`, `zip/xml-zip`, or the generic `zip/zipper` for a custom tree. section 8.4.4
  • Navigate with `zip/up`, `zip/down`, `zip/left`, and `zip/right`; a move with no available destination can return `nil`. section 8.4.4
  • Edit with `zip/replace`, `zip/edit`, `zip/remove`, or insertion functions. Inserting a child at a leaf throws an exception. section 8.4.4

Edit one vector child

`(-> (zip/vector-zip [1 2 [3 4]]) zip/down zip/rightmost (zip/edit conj 5) zip/root)` returns `[1 2 [3 4 5]]`. section 8.4.4

Unlike `clojure.walk`, a zipper does not require a depth-first traversal: move only where needed, or use `zip/next` and `zip/prev` for depth-first movement. section 8.4.4

How Clojure: The Essential Reference covers it

How deep it goes
Works through navigation, edits, custom construction, and traversal, without detailing the implementation internals.
Examples
Demonstrates vector, sequence, XML, and custom-tree zippers with navigation and editing results.
What you can do after
Apply it via `clojure.zip` to navigate and update nested data without mutating the input.
How it connects
Connects tree traversal and functional updates to `clojure.walk` and XML data.

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.