Avatar of stillleben

stillleben's solution

to Zipper in the Scala Track

Published at Sep 06 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)

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command sbt test in the exercise directory.

For more detailed info about the Scala track 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.

ZipperTest.scala

import org.scalatest.{FunSuite, Matchers}

/** @version created manually **/
class ZipperTest extends FunSuite with Matchers {
  def empty[A]: Option[BinTree[A]] = None

  def bt[A](v: A, l: Option[BinTree[A]], r: Option[BinTree[A]]): Option[BinTree[A]] =
    Some(BinTree(v, l, r))

  def leaf[A](v: A): Option[BinTree[A]] =
    Some(BinTree(v, None, None))

  val t1: BinTree[Int] = BinTree(1, bt(2, empty,   leaf(3)), leaf(4))
  val t2: BinTree[Int] = BinTree(1, bt(5, empty,   leaf(3)), leaf(4))
  val t3: BinTree[Int] = BinTree(1, bt(2, leaf(5), leaf(3)), leaf(4))
  val t4: BinTree[Int] = BinTree(1, leaf(2),                 leaf(4))

  def fromSome[T](o: Option[T]) = o.get

  val z = Zipper

  test("data is retained") {
   z.toTree(z.fromTree(t1)) should be (t1)
  }

  test("left, right and value") {
    pending
    z.value(fromSome(z.right(fromSome(z.left(z.fromTree(t1)))))) should be (3)
  }

  test("dead end") {
    pending
    (z.left(fromSome(z.left(z.fromTree(t1))))) should be (None)
  }

  test("tree from deep focus") {
    pending
    z.toTree(fromSome(z.right(fromSome(z.left(z.fromTree(t1)))))) should be (t1)
  }

  test("setValue") {
    pending
    z.toTree(z.setValue(5, (fromSome(z.left(z.fromTree(t1)))))) should be (t2)
  }

  test("setLeft with Some") {
    pending
    z.toTree(z.setLeft(Some(BinTree(5, None, None)),
        (fromSome(z.left(z.fromTree(t1)))))) should be (t3)
  }

  test("setRight with None") {
    pending
    z.toTree(z.setRight(None, (fromSome(z.left(z.fromTree(t1)))))) should be (t4)
  }

  test("different paths to same zipper") {
    pending
    z.right(fromSome(z.up(fromSome(z.left(z.fromTree(t1)))))) should be
      (z.right(z.fromTree(t1)))
  }
}
object Zipper {
  // A zipper for a binary tree.

  // Get a zipper focussed on the root node.
  def fromTree[A](bt: BinTree[A]): Zipper[A] = Zipper(bt, Nil)

  // Get the complete tree from a zipper.
  def toTree[A](zipper: Zipper[A]): BinTree[A] = zipper.tree

  // Get the value of the focus node.
  def value[A](zipper: Zipper[A]): A = zipper.focusNode.value

  // Get the left child of the focus node, if any.
  def left[A](zipper: Zipper[A]): Option[Zipper[A]] = zipper.left

  // Get the right child of the focus node, if any.
  def right[A](zipper: Zipper[A]): Option[Zipper[A]] = zipper.right

  // Get the parent of the focus node, if any.
  def up[A](zipper: Zipper[A]): Option[Zipper[A]] = zipper.up

  // Set the value of the focus node.
  def setValue[A](v: A, zipper: Zipper[A]): Zipper[A] = zipper.setValue(v)

  // Replace a left child tree.
  def setLeft[A](l: Option[BinTree[A]], zipper: Zipper[A]): Zipper[A] =
    zipper.setLeft(l)

  // Replace a right child tree.
  def setRight[A](r: Option[BinTree[A]], zipper: Zipper[A]): Zipper[A] =
    zipper.setRight(r)

}

case class Zipper[A](tree: BinTree[A], path: List[Direction]) {
  private val focusNode = toFocusNode(tree, path)

  private def setValue(v: A): Zipper[A] =
    Zipper(newTree(tree, path, v), path)

  private def setLeft(l: Option[BinTree[A]]): Zipper[A] =
    Zipper(newTree(tree, path, Left, l), path)

  private def setRight(r: Option[BinTree[A]]): Zipper[A] =
    Zipper(newTree(tree, path, Right, r), path)

  private def left: Option[Zipper[A]] =
    if (focusNode.left.isDefined)
      Some(Zipper(tree, path ++ List(Left)))
    else
      None

  private def right: Option[Zipper[A]] =
    if (focusNode.right.isDefined)
      Some(Zipper(tree, path ++ List(Right)))
    else
      None

  def up: Option[Zipper[A]] =
    if (path.nonEmpty)
      Some(Zipper(tree, path.slice(0, path.length - 1)))
    else
      None

  private def newTree(origTree: BinTree[A],
                      path: List[Direction],
                      newVal: A): BinTree[A] = path match {
    case Nil => origTree.copy(value = newVal)
    case el :: tail if el == Left && origTree.left.isDefined =>
      origTree.copy(left = Some(newTree(origTree.left.get, tail, newVal)))
    case el :: tail if el == Right && origTree.right.isDefined =>
      origTree.copy(right = Some(newTree(origTree.left.get, tail, newVal)))
  }

  private def newTree(origTree: BinTree[A],
                      path: List[Direction],
                      newDirection: Direction,
                      newSubTree: Option[BinTree[A]]): BinTree[A] = path match {
    case Nil if newDirection == Left  => origTree.copy(left = newSubTree)
    case Nil if newDirection == Right => origTree.copy(right = newSubTree)
    case el :: tail if el == Left && origTree.left.isDefined =>
      origTree.copy(
        left = Some(newTree(origTree.left.get, tail, newDirection, newSubTree))
      )
    case el :: tail if el == Right && origTree.right.isDefined =>
      origTree.copy(
        right = Some(newTree(origTree.left.get, tail, newDirection, newSubTree))
      )
  }

  @scala.annotation.tailrec
  private def toFocusNode(tree: BinTree[A], path: List[Direction]): BinTree[A] =
    path match {
      case Nil => tree
      case el :: tail if el == Left && tree.left.isDefined =>
        toFocusNode(tree.left.get, tail)
      case el :: tail if el == Right && tree.right.isDefined =>
        toFocusNode(tree.right.get, tail)
    }

}

sealed trait Direction
case object Left extends Direction
case object Right extends Direction

// A binary tree.
case class BinTree[A](value: A,
                      left: Option[BinTree[A]],
                      right: Option[BinTree[A]])

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?