Skip to content

Instantly share code, notes, and snippets.

@Shinpeim
Created November 9, 2014 16:26
Show Gist options
  • Save Shinpeim/33d69ce07a75d3037e77 to your computer and use it in GitHub Desktop.
Save Shinpeim/33d69ce07a75d3037e77 to your computer and use it in GitHub Desktop.
trait Tree[A]{
def map[B](f: A => B):Tree[B]
def forEach(f: A => Unit):Unit
}
case class Node[A](value:A, left:Tree[A], right:Tree[A]) extends Tree[A] {
def map[B](f: A => B): Node[B] = Node(f(value), left.map(f), right.map(f))
def forEach(f: A => Unit): Unit = {
f(value)
left.forEach(f)
right.forEach(f)
}
}
case class Leaf[A](value:A) extends Tree[A] {
def map[B](f: A => B): Leaf[B] = Leaf(f(value))
def forEach(f: A => Unit): Unit = f(value)
}
val tree: Tree[Int] = Node(
1,
Node(
2,
Leaf(3),
Node(
4,
Leaf(5),
Leaf(6)
)
),
Leaf(7)
)
val newTree = tree.map(_.toString())
newTree.forEach(println)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment