ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

# michaelcmartin's solution

## to Zipper in the Erlang Track

Published at Oct 24 2019 · 0 comments
Instructions
Test suite
Solution

Creating a zipper for a binary tree.

Zippers are a purely functional way of navigating within a data structure and manipulating it. They essentially contain a data structure and a pointer into that data structure (called the focus).

For example given a rose tree (where each node contains a value and a list of child nodes) a zipper might support these operations:

• `from_tree` (get a zipper out of a rose tree, the focus is on the root node)
• `to_tree` (get the rose tree out of the zipper)
• `value` (get the value of the focus node)
• `prev` (move the focus to the previous child of the same parent, returns a new zipper)
• `next` (move the focus to the next child of the same parent, returns a new zipper)
• `up` (move the focus to the parent, returns a new zipper)
• `set_value` (set the value of the focus node, returns a new zipper)
• `insert_before` (insert a new subtree before the focus node, it becomes the `prev` of the focus node, returns a new zipper)
• `insert_after` (insert a new subtree after the focus node, it becomes the `next` of the focus node, returns a new zipper)
• `delete` (removes the focus node and all subtrees, focus moves to the `next` node if possible otherwise to the `prev` node if possible, otherwise to the parent node, returns a new zipper)

## Running tests

In order to run the tests, issue the following command from the exercise directory:

For running the tests provided, `rebar3` is used as it is the official build and dependency management tool for erlang now. Please refer to the tracks installation instructions on how to do that.

In order to run the tests, you can issue the following command from the exercise directory.

``````\$ rebar3 eunit
``````

## Questions?

For detailed information about the Erlang track, please refer to the help page on the Exercism site. This covers the basic information on setting up the development environment expected by the exercises.

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### zipper_tests.erl

``````-module(zipper_tests).

-include_lib("erl_exercism/include/exercism.hrl").
-include_lib("eunit/include/eunit.hrl").

%% Fixtures and helpers

bt(V, L, R) -> zipper:new_tree(V, L, R).
empty() -> nil.
leaf(V) -> zipper:new_tree(V, empty(), empty()).

t1() -> bt(1, bt(2, empty(), leaf(3)), leaf(4)).
t2() -> bt(1, bt(5, empty(), leaf(3)), leaf(4)).
t3() -> bt(1, bt(2, leaf(5), leaf(3)), leaf(4)).
t4() -> bt(1, leaf(2),                 leaf(4)).
t5() -> bt(1, bt(2, empty(), leaf(3)), bt(6, leaf(7), leaf(8))).
t6() -> bt(1, bt(2, empty(), leaf(5)), leaf(4)).

data_is_retained_test() ->
Exp = t1(),
?assertMatch(Exp, zipper:to_tree(zipper:from_tree(t1()))).

left_right_and_value_test() ->
?assertMatch(3, zipper:value(zipper:right(zipper:left(zipper:from_tree(t1()))))).

Exp = empty(),
?assertMatch(Exp, zipper:left(zipper:left(zipper:from_tree(t1())))).

tree_from_deep_focus_test() ->
Exp = t1(),
Zipper = zipper:right(zipper:left(zipper:from_tree(t1()))),
?assertMatch(Exp, zipper:to_tree(Zipper)).

traversing_up_from_top_test() ->
Exp = empty(),
?assertMatch(Exp, zipper:up(zipper:from_tree(t1()))).

left_right_and_up_test() ->
Act0 = zipper:from_tree(t1()),
Act1 = zipper:left(Act0),
Act2 = zipper:up(Act1),
Act3 = zipper:right(Act2),
Act4 = zipper:up(Act3),
Act5 = zipper:left(Act4),
Act6 = zipper:right(Act5),
?assertMatch(3, zipper:value(Act6)).

set_value_test() ->
Exp  = t2(),
Act0 = zipper:from_tree(t1()),
Act1 = zipper:left(Act0),
Act2 = zipper:set_value(Act1, 5),
Act3 = zipper:to_tree(Act2),
?assertMatch(Exp, Act3).

set_value_after_traversiing_up_test() ->
Exp  = t2(),
Act0 = zipper:from_tree(t1()),
Act1 = zipper:left(Act0),
Act2 = zipper:right(Act1),
Act3 = zipper:up(Act2),
Act4 = zipper:set_value(Act3, 5),
Act5 = zipper:to_tree(Act4),
?assertMatch(Exp, Act5).

set_left_with_leaf_test() ->
Exp  = t3(),
Act0 = zipper:from_tree(t1()),
Act1 = zipper:left(Act0),
Act2 = zipper:set_left(Act1, leaf(5)),
Act3 = zipper:to_tree(Act2),
?assertMatch(Exp, Act3).

set_right_with_empty_test() ->
Exp  = t4(),
Act0 = zipper:from_tree(t1()),
Act1 = zipper:left(Act0),
Act2 = zipper:set_right(Act1, empty()),
Act3 = zipper:to_tree(Act2),
?assertMatch(Exp, Act3).

set_right_with_subtree_test() ->
Exp  = t5(),
Act0 = zipper:from_tree(t1()),
Act1 = zipper:set_right(Act0, bt(6, leaf(7), leaf(8))),
Act2 = zipper:to_tree(Act1),
?assertMatch(Exp, Act2).

set_value_from_deep_focus_test() ->
Exp  = t6(),
Act0 = zipper:from_tree(t1()),
Act1 = zipper:left(Act0),
Act2 = zipper:right(Act1),
Act3 = zipper:set_value(Act2, 5),
Act4 = zipper:to_tree(Act3),
?assertMatch(Exp, Act4).``````
``````-module(zipper).

-export([new_tree/3, from_tree/1, to_tree/1, up/1, left/1, right/1, value/1, set_value/2, set_left/2, set_right/2, test_version/0]).

%%% Our tree datatype is a triple { V, L, R } where
%%%    - V is the value at this point in the rose tree
%%%    - L is the subtree to the left
%%%    - R is the subtree to the right
%%% Subtrees that do not exist are the symbol 'nil'.

new_tree(Value, Left, Right) ->
{ Value, Left, Right }.

%%% The fundamental concept of a zipper is that it is a datatype and a
%%% path within that datatype representing a specific point within
%%% it. For a binary tree, we store a reference directly to the node
%%% at the end of the path, and then keep a list of every parent node
%%% back to the root. While it is technically redundant to do so, we
%%% also keep track of the direction we take at each parent node to
%%% move further down the path, because it makes pattern matching
%%% *much* easier. We use the symbols 'l' and 'r' to indicate
%%% left/right in the path.
%%%
%%% A zipper is thus a pair; the path list, and the focus node.

%%% To create a zipper from a tree, we create an empty path and focus
%%% on the root node.
from_tree(Tree) ->
{ [], Tree }.

%%% And to reverse the operation, we traverse up the tree until we run
%%% the path empty, and then return the focus node as the root.
to_tree({ [], Tree }) -> Tree;
to_tree(Zipper) -> to_tree(up(Zipper)).

%%% By caching the focus node directly, extracting the value is a
%%% simple destructuring operation.
value({ _, { V, _ , _ } }) ->
V.

%%% Moving left or right in the tree requires destructuring out the
%%% target subtree, and adding the necessary direction to the access
%%% path. The test suite insists that walking off the edge of the tree
%%% does not return a path to a nil node, but instead returns a zipper
%%% that *is itself* nil. We replicate that, and we also make it
%%% legal, but a no-op, to attempt to navigate nil.
left({ Path, Node}) ->
{ _, L, _ } = Node,
case L of
{ _, _, _ } ->
{ [{l, Node}|Path], L };
_Else ->
nil
end;
left(nil) ->
nil.

right({ Path, Node }) ->
{ _, _, R } = Node,
case R of
{ _, _, _ } ->
{ [{r, Node}|Path], R };
_Else ->
nil
end;
right(nil) ->
nil.

%%% Meanwhile, navigating up involves throwing away our current focus
%%% node and extracing the parent, and the path to it, from our access
%%% path. Similarly to the left/right cases, attempting to go up from
%%% root or nil produces a nil zipper as well.
up({ [{_, Up}|UpPath], _ }) ->
{ UpPath, Up };
up({ [], _ }) ->
nil;
up(nil) ->
nil.

%%% Editing the tree that the zipper is pointed at involves creating a
%%% new tree node and building a new tree with that node slotted into
%%% the correct place. We may retain all unaltered subtrees, so in
%%% practice this means that our task is to create new nodes for
%%% ourself (provided as the NewNode argument to splice/2) and all our
%%% parents (conveniently arranged in order for us by Zipper's access
%%% path). The splice/2 function performs this tree-replacement
%%% operation, and the three exported editing functions are built in
%%% terms of it.
splice(Zipper, NewNode) ->
{ ZipPath, _ } = Zipper,
case ZipPath of
[] ->
%% Base case: If we're replacing the root, that's just
%% creating a new zipper from our replacement tree.
from_tree(NewNode);
[{ l, UpNode }|_Rest] ->
%% If we moved left from our immediate parent to get to
%% this node, splice in a new parent that keeps its value
%% and right child but points to us as its new left
%% child. Then follow the newly-spliced parent node to get
%% a zipper focused on NewNode itself.
UpZip = up(Zipper),
{ UpVal, _, UpRight } = UpNode,
NewUp = { UpVal, NewNode, UpRight },
left(splice(UpZip, NewUp));
[{ r, UpNode }|_Rest] ->
%% If we moved right from our immediate parent to get to
%% this node, the procudure is broadly similar to the left
%% case, just retaining the other child instead.
UpZip = up(Zipper),
{ UpVal, UpLeft, _ } = UpNode,
NewUp = { UpVal, UpLeft, NewNode },
right(splice(UpZip, NewUp))
end.

%%% The set_value/2, set_left/2, and set_right/2 functions are all
%%% very similar, extracting the two preserved values from the Zipper
%%% argument, creating a new node that combines those two values with
%%% the Value argument, and then splicing that new node into place.

set_value(Zipper, Value) ->
{ _, { _, L, R } } = Zipper,
splice(Zipper, { Value, L, R }).

set_left(Zipper, Value) ->
{ _, { V, _, R } } = Zipper,
splice(Zipper, { V, Value, R }).

set_right(Zipper, Value) ->
{ _, { V, L, _ } } = Zipper,
splice(Zipper, { V, L, Value }).

test_version() -> 1.``````