Skip to content

Instantly share code, notes, and snippets.

@hoffrocket
Created March 13, 2009 04:22
Show Gist options
  • Save hoffrocket/78427 to your computer and use it in GitHub Desktop.
Save hoffrocket/78427 to your computer and use it in GitHub Desktop.
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