summaryrefslogtreecommitdiff
path: root/docs/examples/patterns.scala
blob: d082fcc3de7e223d5260e8cb1d648f8367c93d2f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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[Tuple2[a, b]], x: a): Option[b] = {
    var result: Option[b] = None
    var found = false
    while (it.hasNext && !found) {
      val (x1, y) = it.next
      if (x == x1) { found = true; result = Some(y) }
    }
    result
  }

  def printFinds[a](xs: List[Tuple2[a, String]], x: a) =
    find(xs.iterator, x) match {
      case Some(y) => System.out.println(y)
      case None => System.out.println("no match")
    }

  def main(args: Array[String]) {
    println("sum of leafs=" + sumLeaves(tree1))
    printFinds(List((3, "three"), (4, "four")), 4)
  }
}