Avatar of zvkemp
0
1
Genius
0
3

zvkemp's solution

to Zipper in the Elixir Track

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

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
  @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
end

defmodule Zipper do
  @type t :: %Zipper{ focus: BinTree.t, history: List.t }
  defstruct focus: nil, history: []
  @doc """
  Get a zipper focused on the root node.
  """

  alias Zipper, as: Z

  @spec from_tree(BT.t) :: Z.t
  def from_tree(bt) do
    %Z{ focus: bt }
  end

  @doc """
  Get the complete tree from a zipper.
  """
  @spec to_tree(Z.t) :: BT.t
  def to_tree(%Z{ focus: bt, history: [] }), do: bt
  def to_tree(z) do
    z |> up |> to_tree
  end

  @doc """
  Get the value of the focus node.
  """
  @spec value(Z.t) :: any
  def value(%Z{ focus: %{ value: v }}), do: v
  def value(_), do: nil

  @doc """
  Get the left child of the focus node, if any.
  """
  @spec left(Z.t) :: Z.t | nil
  def left(z), do: get(z, :left)

  @doc """
  Get the right child of the focus node, if any.
  """
  @spec right(Z.t) :: Z.t | nil
  def right(z), do: get(z, :right)

  @doc """
  Get the parent of the focus node, if any.
  """
  @spec up(Z.t) :: Z.t
  def up(%Z{ focus: bt, history: [{direction, h}|hs] }) do
    %Z{ history: hs, focus: Map.put(h, direction, bt) }
  end

  @doc """
  Set the value of the focus node.
  """
  @spec set_value(Z.t, any) :: Z.t
  def set_value(z, v), do: put(z, v, :value)

  @doc """
  Replace the left child tree of the focus node.
  """
  @spec set_left(Z.t, BT.t) :: Z.t
  def set_left(z, l), do: put(z, l, :left)

  @doc """
  Replace the right child tree of the focus node.
  """
  @spec set_right(Z.t, BT.t) :: Z.t
  def set_right(z, r), do: put(z, r, :right)

  defp put(%Z{ focus: bt } = z, value, position) do
    %{ z | focus: Map.put(bt, position, value) }
  end

  defp get(%Z{ focus: bt, history: h }, direction) do
    case Map.pop(bt, direction) do
      { nil, _ } -> nil
      { v, new } -> %Z{ focus: v, history: [{ direction, new } | h ] }
    end
  end
end

What can you learn from this solution?

A huge amount can be learnt 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 I could read more about to develop my understanding?

Community comments

See what others have said about this solution
almost 3 years ago
zvkemp says

Thanks for your comments @petertseng! Here's an implementation that uses Map.pop to avoid the duplication of data where possible. One consequence of this is that the resultant BT structs no longer have their complete set of keys, so I had to change the inspect implementation in the test suite:
def inspect(%BinTree{value: v} = bt, opts) do
concat ["(", to_doc(v, opts),
":", (if l = Map.get(bt, :left), do: to_doc(l, opts), else: ""),
":", (if r = Map.get(bt, :right), do: to_doc(r, opts), else: ""),
")"]
end

It's a bit surprising to me that a struct defined with default values would raise a KeyError even if the key is popped out.

almost 3 years ago
zvkemp says

Yeah, I played with put too, but I like that the read and update can be done with the single operation of pop.

almost 3 years ago
petertseng says

Interesting point about the default values. I guess the defaults are only provided at creation time? I will need to read a bit more before able to answer that question.

I suppose if you wanted to make this work without modifying the tests then maybe Map.put(new, direction, nil) might have been an option, but I don't find that really necessary.