Skip to content

Instantly share code, notes, and snippets.

@sshark
Last active August 29, 2015 07:45
Show Gist options
  • Select an option

  • Save sshark/6225e22bdc54e1a3c6f9 to your computer and use it in GitHub Desktop.

Select an option

Save sshark/6225e22bdc54e1a3c6f9 to your computer and use it in GitHub Desktop.
Nodes are mirrored and pretty print. It does not work beyond 3 levels. Fixing it...
trait Tree[+A]
case class Node[A](i: A, left: Tree[A], right: Tree[A]) extends Tree[A]
case class Leaf[A](i: A) extends Tree[A]
val tree = Node(4, Leaf(1), Node(7, Node(6, Leaf(3), Leaf(4)), Node(8, Leaf(1), Leaf(1))))
def mirror[A](node: Tree[A]): Tree[A] = {
node match {
case n: Node[A] => Node(n.i, mirror(n.right), mirror(n.left))
case l: Leaf[A] => Leaf(l.i)
}
}
def pp[A](node: Tree[A]): List[List[A]] = {
def _pp[A](node: Tree[A], ll: List[List[A]]): List[List[A]] = {
node match {
case n: Node[A] => (n.left, n.right) match {
case (l: Leaf[A], r: Leaf[A]) => List(l.i, r.i) :: ll
case (l: Node[A], r: Leaf[A]) => _pp(l, List(l.i, r.i) :: ll)
case (l: Leaf[A], r: Node[A]) => _pp(r, List(l.i, r.i) :: ll)
case (l: Node[A], r: Node[A]) => _pp(l, List(l.i, r.i) :: ll).zip(_pp(r, List(l.i, r.i) :: ll)).map( x => (x._1 ++ x._2)) // FIXME
}
}
}
node match {
case n: Node[A] => _pp(n, List(List(n.i)))
case l: Leaf[A] => List(List(l.i))
}
}
pp(tree).reverse
pp(mirror(tree)).reverse
val l = List(List(2,3)).zip(List(List(4,5))).map( x => (x._1 ++ x._2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment