Created
June 21, 2012 17:59
-
-
Save dholbrook/2967371 to your computer and use it in GitHub Desktop.
Scala binary tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package scalaninetynine | |
abstract class Tree[+A] { | |
def value: Option[A] = this match { | |
case n: Node[A] => Some(n.v) | |
case l: Leaf[A] => Some(l.v) | |
case Empty => None | |
} | |
def left: Option[Tree[A]] = this match { | |
case n: Node[A] => Some(n.l) | |
case l: Leaf[A] => None | |
case Empty => None | |
} | |
def right: Option[Tree[A]] = this match { | |
case n: Node[A] => Some(n.r) | |
case l: Leaf[A] => None | |
case Empty => None | |
} | |
def count: Int = { | |
def loop(t: Tree[_]): Int = t match { | |
case n: Node[_] => Seq(loop(n.left.get), loop(n.right.get)).sum + 1 | |
case l: Leaf[_] => 1 | |
case Empty => 0 | |
} | |
loop(this) | |
} | |
} | |
case class Node[A](v: A, l: Tree[A], r: Tree[A]) extends Tree | |
case class Leaf[A](v: A) extends Tree | |
case object Empty extends Tree[Nothing] | |
object Run extends App { | |
val t: Tree[Symbol] = Node('A, Node('B, Leaf('D), Leaf('E)), Node('C, Empty, Node('F, Leaf('G), Empty))) | |
println("tree: " + t) | |
//print the value of b node navigating from root | |
for { | |
b <- t.left | |
value <- b.value | |
} println("B node: " + value) | |
//print the value of e node navigating from root | |
for { | |
b <- t.left | |
e <- b.right | |
value <- e.value | |
} println("E node: " + value) | |
//no println() is executed for empty node chain | |
for { | |
b <- t.left | |
e <- b.right | |
x <- e.right //no node here | |
value <- x.value | |
} println("X node SHOUL NOT PRINT!: " + value) | |
println("count " + t.count) | |
/****** output ********* | |
tree: Node('A,Node('B,Leaf('D),Leaf('E)),Node('C,Empty,Node('F,Leaf('G),Empty))) | |
B node: 'B | |
E node: 'E | |
count 7 | |
*************************/ | |
} |
🎉
Would some one please show my how to use foldLoop or fold to return a modified tree?
Good job!
Exquisite.
very cool, nice work :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Beautiful.