Created
November 9, 2014 16:26
-
-
Save Shinpeim/33d69ce07a75d3037e77 to your computer and use it in GitHub Desktop.
This file contains 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
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