# What is a zipper, and how does it relate to a tree-like structure?

I was reading a chapter in LYAH which didn't really make sense to me. I understand that zippers can arbitrarily traverse a tree-like structure, but I need some clarification on it. Also, can zippers be generalized to any data structure?

-
This is probably more appropriate for Computer Science, though the work generalising zippers involves quite some technical machinery. –  Dave Clarke Dec 8 '12 at 20:59
A zipper is something that you should always keep closed, especially when traversing a tree. –  Andrej Bauer Dec 8 '12 at 22:44

A zipper, in general, is a data structure with a hole in it. Zippers are used for traversing/manipulating data structures, and the hole corresponds to the current focus of the traversal. Typically there is also an element of the data structure under consideration, so that one has a (list) zipper and a list or a (tree) zipper and a tree. The zipper allows the programmer to efficiently move around the data structure, even replacing the element at the focus. The pair of the zipper and the element in the focus satisfy the constraint that placing the element at the focus in the hole gives the original data structure.

Zippers can be generalised to arbitrary inductive data types. The concept can be defined in type-indexed fashion (See type-indexed data types). They are also related to the idea of the derivative of a data structure, and has been studied from a Category Theoretic perspective.

-

A zipper is in general a pair of things: it's a structure-with-a-hole, a focus, representing where in the structure you are, together with a path, recording how you got to that focus. (This path is LYAH's trail of breadcrumbs.)

The path is how you actually apply changes to the structure: "go down, go left, increment the value". By repeatedly applying "go up" (go_up in Huet's paper) at this point, you can retrace your steps and end up with a new, mutated, copy of the original structure.

They can indeed be generalised to other structures: * Scrap Your Zippers uses generic programming in Haskell * Clojure's zipper gives you a "pluggable" zipper: when you create a zipper on a structure, you pass in functions specific to your structure

-