Avatar of numberMumbler

numberMumbler's solution

to Zipper in the Elixir Track

Published at Jun 12 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

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

If you're stuck on something, it may help to look at some of the available resources out there where answers might be found.

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
    zipper = t1() |> from_tree() |> left() |> up() |> right() |> up() |> left() |> right()
    assert value(zipper) == 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
  @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: t() | nil, right: t() | nil}

  defstruct [:value, :left, :right]
end

defimpl Inspect, for: BinTree do
  import Inspect.Algebra

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

defmodule Zipper do
  @type t :: %Zipper{focus: BinTree.t(), path: Enum.t()}

  defstruct [:focus, :path]

  @doc """
  Get a zipper focused on the root node.
  """
  @spec from_tree(BinTree.t()) :: Zipper.t()
  def from_tree(bin_tree) do
    %Zipper{focus: bin_tree, path: []}
  end

  @doc """
  Get the complete tree from a zipper.
  """
  @spec to_tree(Zipper.t()) :: BinTree.t()
  def to_tree(%Zipper{focus: focus, path: []}) do
    focus
  end

  def to_tree(%Zipper{path: [{parent, _} | ancestors]}) do
    to_tree(%Zipper{focus: parent, path: ancestors})
  end

  @doc """
  Get the value of the focus node.
  """
  @spec value(Zipper.t()) :: any
  def value(%Zipper{focus: focus}) do
    focus.value
  end

  @doc """
  Get the left child of the focus node, if any.
  """
  @spec left(Zipper.t()) :: Zipper.t() | nil
  def left(%Zipper{focus: %BinTree{left: nil}}) do
    nil
  end

  def left(%Zipper{focus: focus, path: path}) do
    %Zipper{focus: focus.left, path: [{focus, :left} | path]}
  end

  @doc """
  Get the right child of the focus node, if any.
  """
  @spec right(Zipper.t()) :: Zipper.t() | nil
  def right(%Zipper{focus: %BinTree{right: nil}}) do
    nil
  end

  def right(%Zipper{focus: focus, path: path}) do
    %Zipper{focus: focus.right, path: [{focus, :right} | path]}
  end

  @doc """
  Get the parent of the focus node, if any.
  """
  @spec up(Zipper.t()) :: Zipper.t() | nil
  def up(%Zipper{path: []}) do
    nil
  end

  def up(%Zipper{path: [{parent, _} | ancestors]}) do
    %Zipper{focus: parent, path: ancestors}
  end

  @doc """
  Set the value of the focus node.
  """
  @spec set_value(Zipper.t(), any) :: Zipper.t()
  def set_value(zipper, value) do
    update_focus(zipper, :value, value)
  end

  @doc """
  Replace the left child tree of the focus node.
  """
  @spec set_left(Zipper.t(), BinTree.t() | nil) :: Zipper.t()
  def set_left(zipper, left) do
    update_focus(zipper, :left, left)
  end

  @doc """
  Replace the right child tree of the focus node.
  """
  @spec set_right(Zipper.t(), BinTree.t() | nil) :: Zipper.t()
  def set_right(zipper, right) do
    update_focus(zipper, :right, right)
  end

  # common functions to propagate node changes
  defp update_focus(zipper, field, value) do
    updated_node = update_field(zipper.focus, field, value)
    updated_path = update_path(updated_node, zipper.path)

    %Zipper{focus: updated_node, path: updated_path}
  end

  defp update_field(node, :value, value), do: %{node | value: value}
  defp update_field(node, :left, value), do: %{node | left: value}
  defp update_field(node, :right, value), do: %{node | right: value}

  defp update_path(_, []) do
    []
  end

  defp update_path(updated_node, [{parent_node, parent_direction} | ancestors]) do
    parent_zipper = %Zipper{focus: parent_node, path: ancestors}
    updated_zipper = update_focus(parent_zipper, parent_direction, updated_node)

    [{updated_zipper.focus, parent_direction} | updated_zipper.path]
  end
end

Community comments

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

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?