diff options
author | Gilles Dubochet <gilles.dubochet@epfl.ch> | 2005-12-16 18:44:33 +0000 |
---|---|---|
committer | Gilles Dubochet <gilles.dubochet@epfl.ch> | 2005-12-16 18:44:33 +0000 |
commit | 53a3cc7b17f4cf97075b7e71720777fd84109696 (patch) | |
tree | 0cc784e0b47ea49cc151a136d19f20bfa8ee2197 /docs/examples/patterns.scala | |
parent | df50e05006b43b007c2587549030d24b5c154398 (diff) | |
download | scala-53a3cc7b17f4cf97075b7e71720777fd84109696.tar.gz scala-53a3cc7b17f4cf97075b7e71720777fd84109696.tar.bz2 scala-53a3cc7b17f4cf97075b7e71720777fd84109696.zip |
Created proper 'docs' folder for new layout.
Diffstat (limited to 'docs/examples/patterns.scala')
-rw-r--r-- | docs/examples/patterns.scala | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/docs/examples/patterns.scala b/docs/examples/patterns.scala new file mode 100644 index 0000000000..34b0db96ae --- /dev/null +++ b/docs/examples/patterns.scala @@ -0,0 +1,35 @@ +package examples; + +object patterns { + + trait Tree; + case class Branch(left: Tree, right: Tree) extends Tree; + case class Leaf(x: Int) extends Tree; + + val tree1 = Branch(Branch(Leaf(1), Leaf(2)), Branch(Leaf(3), Leaf(4))); + + def sumLeaves(t: Tree): Int = t match { + case Branch(l, r) => sumLeaves(l) + sumLeaves(r) + case Leaf(x) => x + } + + def find[a,b](it: Iterator[Pair[a, b]], x: a): Option[b] = { + var result: Option[b] = _; + while (it.hasNext && result == null) { + val Pair(x1, y) = it.next; + if (x == x1) result = Some(y) + } + if (result == null) None else result + } + + def printFinds[a](xs: List[Pair[a, String]], x: a) = + find(xs.elements, x) match { + case Some(y) => System.out.println(y) + case None => System.out.println("no match") + } + + def main(args: Array[String]): Unit = { + Console.println("sum of leafs=" + sumLeaves(tree1)); + printFinds(List(Pair(3, "three"), Pair(4, "four")), 4) + } +}
\ No newline at end of file |