Created
March 13, 2009 04:22
-
-
Save hoffrocket/78427 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
case class Tree[A](datum:A, children:List[Tree[A]]) { | |
def map[B](fn: A => B): Tree[B] = { | |
new Tree[B](fn(datum),children.map(_.map(fn))) | |
} | |
def foreach(fn: A => Unit) { | |
fn(datum) | |
children.foreach(_.foreach(fn)) | |
} | |
def exists(a: A): Boolean = { | |
datum.equals(a) || children.exists(_.exists(a)) | |
} | |
} | |
// create: | |
// 1 | |
// / \ | |
// 2 3 | |
val tree = Tree(1,List(Tree(2,Nil),Tree(3,Nil))) | |
val squareTree = tree.map(a => a*a) | |
assertTrue(tree.exists(3)) | |
assertTrue(squareTree.exists(9)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment