2

I am reading the Zipper article in Haskell Wiki and I can't understand the up method defined as:

data Tree a = Fork (Tree a) (Tree a) | Leaf a

data Cxt a = Top | L (Cxt a) (Tree a) | R (Tree a) (Cxt a)

type Loc a = (Tree a, Cxt a)

up :: Loc a -> Loc a
up (t, L c r) = (Fork t r, c)
up (t, R l c) = (Fork l t, c)

In the pattern up (t, L c r), t is the subtree with focus, c is the context with a hole at current focus, when moving up, why c doesn't move up but still referenced to the old context? Shouldn't the focus also go up?

Sawyer
  • 15,581
  • 27
  • 88
  • 124

1 Answers1

2

In

up (t, L c r) = (Fork t r, c)

not c is the current context, but L c r is. The context describes a path from your current tree to the root. A context of form L c r originates from descending into a left subtree, so in order to go up one layer, we have to combine it with the corresponding right subtree r. The c is the remaining path up to the root, and therefore becomes the new context.

Let's look at a small example: assume you have a tree that looks like this:

   *
  / \
 /   \
/ \ / \
1 2 3 4

It would be represented using the Tree type as

tree = Fork (Fork (Leaf 1) (Leaf 2))
            (Fork (Leaf 3) (Leaf 4))

Now the location where Leaf 3 is selected in the tree looks as follows:

loc3 = (Leaf 3, L (R (Fork (Leaf 1) (Leaf 2)) Top) (Leaf 4))

Note that the context here is of the form

L c (Leaf 4)

indicating that on the path from your current node up you are in the left subtree of the parent node, and the corresponding right subtree is Leaf 4. The c is the context for the remaining steps, in this case that the tree Fork (Leaf 3) (Leaf 4) is actually the right subtree of the complete tree.

kosmikus
  • 19,549
  • 3
  • 51
  • 66
  • I asked the same question on SO two years ago and I was not convinced by your answer then, now I accept both. Thanks. – Sawyer Mar 20 '14 at 02:17