Another angle on zippers
The zipper is an efficient and elegant data structure for purely functional editing of tree-like data structures, first published by Gérard Huet. Zippers maintain a location of focus in a tree and support navigation operations (up, down, left, right) and editing (replace current focus).
The original zipper type and operations are customized for a single type, but it’s not hard to see how to adapt to other tree-like types, and hence to regular data types. There have been many follow-up papers to The Zipper, including a polytypic version in the paper Type-indexed data types.
All of the zipper adaptations and generalizations I’ve seen so far maintain the original navigation interface. In this post, I propose an alternative interface that appears to significantly simplify matters. There are only two navigation functions instead of four, and each of the two is specified and implemented via a fairly simple one-liner.
I haven’t used this new zipper formulation in an application yet, so I do not know whether some usefulness has been lost in simplifying the interface.
The code in this blog post is taken from the Haskell library functor-combo and completes the Holey
type class introduced in Differentiation of higher-order types.
Edits:
- 2010-07-29: Removed some stray
Just
applications inup
definitions. (Thanks, illissius.) - 2010-07-29: Augmented my complicated definition of
tweak2
with a much simpler version from Sjoerd Visscher. - 2010-07-29: Replaced
fmap (first (:ds'))
with(fmap.first) (:ds')
indown
definitions. (Thanks, Sjoerd.)