Avatar of davearonson

davearonson's solution

to Zipper in the Elixir Track

Published at Jul 13 2018 · 1 comment
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

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

Execute the tests with:

$ elixir zipper_test.exs

Pending tests

In the test suites, all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by commenting out the relevant @tag :pending with a # symbol.

For example:

# @tag :pending
test "shouting" do
  assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end

Or, you can enable all the tests by commenting out the ExUnit.configure line in the test suite.

# ExUnit.configure exclude: :pending, trace: true

For more detailed information about the Elixir track, please see the help page.

Submitting Incomplete Solutions

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

zipper_test.exs

if !System.get_env("EXERCISM_TEST_EXAMPLES") do
  Code.load_file("zipper.exs", __DIR__)
end

ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)

defmodule ZipperTest do
  alias BinTree, as: BT
  import Zipper
  use ExUnit.Case

  defp bt(value, left, right), do: %BT{value: value, left: left, right: right}
  defp leaf(value), do: %BT{value: value}

  defp t1, do: bt(1, bt(2, nil, leaf(3)), leaf(4))
  defp t2, do: bt(1, bt(5, nil, leaf(3)), leaf(4))
  defp t3, do: bt(1, bt(2, leaf(5), leaf(3)), leaf(4))
  defp t4, do: bt(1, leaf(2), leaf(4))
  defp t5, do: bt(1, bt(2, nil, leaf(3)), bt(6, leaf(7), leaf(8)))
  defp t6, do: bt(1, bt(2, nil, leaf(5)), leaf(4))

  # @tag :pending
  test "data is retained" do
    assert t1() |> from_tree |> to_tree == t1()
  end

  @tag :pending
  test "left, right and value" do
    assert t1() |> from_tree |> left |> right |> value == 3
  end

  @tag :pending
  test "dead end" do
    assert t1() |> from_tree |> left |> left == nil
  end

  @tag :pending
  test "tree from deep focus" do
    assert t1() |> from_tree |> left |> right |> to_tree == t1()
  end

  @tag :pending
  test "traversing up from top" do
    assert t1() |> from_tree |> up == nil
  end

  @tag :pending
  test "left, right, and up" do
    assert t1() |> from_tree |> left |> up |> right |> up |> left |> right |> value == 3
  end

  @tag :pending
  test "set_value" do
    assert t1() |> from_tree |> left |> set_value(5) |> to_tree == t2()
  end

  @tag :pending
  test "set_value after traversing up" do
    assert t1() |> from_tree |> left |> right |> up |> set_value(5) |> to_tree == t2()
  end

  @tag :pending
  test "set_left with leaf" do
    assert t1() |> from_tree |> left |> set_left(leaf(5)) |> to_tree == t3()
  end

  @tag :pending
  test "set_right with nil" do
    assert t1() |> from_tree |> left |> set_right(nil) |> to_tree == t4()
  end

  @tag :pending
  test "set_right with subtree" do
    assert t1() |> from_tree |> set_right(bt(6, leaf(7), leaf(8))) |> to_tree == t5()
  end

  @tag :pending
  test "set_value on deep focus" do
    assert t1() |> from_tree |> left |> right |> set_value(5) |> to_tree == t6()
  end
end
defmodule BinTree do
  import Inspect.Algebra
  @moduledoc """
  A node in a binary tree.

  `value` is the value of a node.
  `left` is the left subtree (nil if no subtree).
  `right` is the right subtree (nil if no subtree).
  """
  @type t :: %BinTree{ value: any, left: BinTree.t | nil, right: BinTree.t | nil }
  defstruct value: nil, left: nil, right: nil

  # A custom inspect instance purely for the tests, this makes error messages
  # much more readable.
  #
  # BT[value: 3, left: BT[value: 5, right: BT[value: 6]]] becomes (3:(5::(6::)):)
  def inspect(%BinTree{value: v, left: l, right: r}, opts) do
    concat ["(", to_doc(v, opts),
            ":", (if l, do: to_doc(l, opts), else: ""),
            ":", (if r, do: to_doc(r, opts), else: ""),
            ")"]
  end
end

defmodule Zipper do
  alias BinTree, as: BT
  defstruct data: nil, path: nil, dirs: nil
  @doc """
  Get a zipper focused on the root node.
  """
  @spec from_tree(BT.t) :: Z.t
  def from_tree(bt) do
    %Zipper{ data: bt, path: [bt], dirs: [] }
  end

  @doc """
  Get the complete tree from a zipper.
  """
  @spec to_tree(Z.t) :: BT.t
  def to_tree(z) do
    z.data
  end

  @doc """
  Get the value of the focus node.
  """
  @spec value(Z.t) :: any
  def value(%Zipper{path: [head|_tail]}) do
    head.value
  end

  @doc """
  Get the left child of the focus node, if any.
  """
  @spec left(Z.t) :: Z.t | nil
  def left(  %Zipper{path: [%BT{left: nil  }|_tail]}), do: nil
  def left(z=%Zipper{path: [%BT{left: lefty}|_tail]})  do
    %Zipper{ z | path: [lefty|z.path], dirs: [:left|z.dirs] }
  end

  @doc """
  Get the right child of the focus node, if any.
  """
  def right(  %Zipper{path: [%BT{right: nil   }|_tail]}), do: nil
  def right(z=%Zipper{path: [%BT{right: righty}|_tail]})  do
    %Zipper{ z | path: [righty|z.path], dirs: [:right|z.dirs] }
  end

  @doc """
  Get the parent of the focus node, if any.
  """
  @spec up(Z.t) :: Z.t
  def up(%Zipper{dirs: []}), do: nil
  def up(z=%Zipper{path: [_cur|path_rest], dirs: [_curdir|dirs_rest]}) do
    %Zipper{ z | path: path_rest, dirs: dirs_rest }
  end

  @doc """
  Set the value of the focus node.
  """
  @spec set_value(Z.t, any) :: Z.t
  def set_value(z=%Zipper{path: [head|_tail]}, v) do
    replace_focus(z, %BT{ head | value: v })
  end

  @doc """
  Replace the left child tree of the focus node.
  """
  @spec set_left(Z.t, BT.t) :: Z.t
  def set_left(z=%Zipper{path: [head|_tail]}, l) do
    replace_focus(z, %BT{ head | left: l })
  end

  @doc """
  Replace the right child tree of the focus node.
  """
  @spec set_right(Z.t, BT.t) :: Z.t
  def set_right(z=%Zipper{path: [head|_tail]}, r) do
    replace_focus(z, %BT{ head | right: r })
  end


  defp replace_focus(z=%Zipper{path: [_head|tail]}, new_head) do
    %Zipper{ z | data: update_tree(tail, z.dirs, new_head),
                 path: [new_head | tail] }
  end

  defp update_tree([path_head|path_tail], [dirs_head|dirs_tail], sub) do
    new_sub = case dirs_head do
                :left  -> %BT{ path_head | left:  sub }
                :right -> %BT{ path_head | right: sub }
              end
    update_tree(path_tail, dirs_tail, new_sub)
  end
  defp update_tree([], [], sub), do: sub

end

Community comments

Find this solution interesting? Ask the author a question to learn more.
Avatar of davearonson

I know there's some stuff that could be DRYed up here with some macros or some such metaprogramming, like combining the set_{left|right|value} functions, but that's one of the things I haven't yet gotten into in Elixir! :-)

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?