Avatar of allaxandr

allaxandr's solution

to Zipper in the Scala Track

Published at Jan 12 2020 · 1 comment
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.

Please see the learning and installation pages if you need any help.

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)))
  }
}

src/main/scala/Zipper.scala

/********************* binary tree *******************/

// must be a package object
object BinTree {
  type BinTree[A] = Option[BinTreeNode[A]]
  // convenience builders
  def empty[A]: BinTree[A] = None
  def tree[A](v: A, l: BinTree[A] = None, r: BinTree[A] = None): BinTree[A] = Some(BinTreeNode(v,l,r))
}

import BinTree._

case class BinTreeNode[A](value: A, left: BinTree[A], right: BinTree[A])

/********************* binary tree zipper *******************/

object BinTreeZipper {
  type ContextNode[A] = BinTree[A] => BinTreeNode[A]
  type Context[A] = List[ContextNode[A]]
}

import BinTreeZipper._

// in the methods, `finger` is abbreviated as `p` (for "pointer"), because `f` is reserved for "function"
case class BinTreeZipper[A](finger: BinTree[A], contexts: Context[A] = Nil) {
  type Zipper = BinTreeZipper[A]
  // restore the tree
  def toTree: BinTree[A] = contexts.foldLeft(finger) {case (p,c) => Some(c(p))}
  // value at the current node
  def value(): Option[A] = finger map (_.value)
  // move methods
  def up: Option[Zipper] =
    Some(contexts) collect {case c::cs => BinTreeZipper(Some(c(finger)), cs)}
  def left: Option[Zipper] = downWith {node => (node.left, x => node.copy(left = x))}
  def right: Option[Zipper] = downWith {node => (node.right, x => node.copy(right = x))}
  // update methods
  def valueUpdated(x: A): Option[Zipper] = updatedWith {_.copy(value = x)}
  def leftUpdated(x: BinTree[A]): Option[Zipper] = updatedWith {_.copy(left = x)}
  def rightUpdated(x: BinTree[A]): Option[Zipper] = updatedWith {_.copy(right = x)}
  // helpers
  private def downWith(f: BinTreeNode[A] => (BinTree[A], ContextNode[A])) = for {
    node <- finger
    (p,c) = f(node)
  } yield BinTreeZipper(p, c::contexts)
  private def updatedWith(f: BinTreeNode[A] => BinTreeNode[A]) =
    finger map {node => copy(finger = Some(f(node)))}
}

src/test/scala/ZipperTest.scala

import org.scalatest.{FunSuite, Matchers}

/** @version created manually **/
class ZipperTest extends FunSuite with Matchers {
  import BinTree.{tree => bt, _}

  // had to shadow Matchers.empty
  def empty[A]: BinTree[A] = BinTree.empty

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

  val Zipper = BinTreeZipper

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

  test("left, right and value") {
    Zipper(t1).left flatMap (_.right) flatMap (_.value) should be (Some(3))
  }

  test("dead end") {
    val r = Zipper(t1).left flatMap (_.left)
    r.isDefined should be (true)
    r flatMap (_.finger) should be (None)
  }

  test("tree from deep focus") {
    Zipper(t1).left flatMap (_.right) flatMap (_.toTree) should be (t1)
  }

  test("setValue") {
    Zipper(t1).left flatMap (_.valueUpdated(5)) flatMap (_.toTree) should be (t2)
  }

  test("setLeft with Some") {
    Zipper(t1).left flatMap (_.leftUpdated(bt(5))) flatMap (_.toTree) should be (t3)
  }

  test("setRight with None") {
    Zipper(t1).left flatMap (_.rightUpdated(empty)) flatMap (_.toTree) should be (t4)
  }

  test("different paths to same zipper") {
    Zipper(t1).left flatMap (_.up) flatMap (_.right) should be
      (Zipper(t1).right)
  }
}

Community comments

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

As the original task contained some incoherences (for instance, it wasn't possible to create an empty binary tree), I allowed to myself creation of data structures that I viewed as correct.

In particular, all the methods went to BinTreeZipper case class. After writing it, I intended to write an adapter object @deprecated object Zipper.

But because in few places types got Option on them, I anyway had to change the tests. I, then, got this as an opportunity to extend the exercise, and rewrote the tests completely. Which made them briefer, cleaner, and more Scala-ish.

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?