alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (patterns.scala)

This example Scala source code file (patterns.scala) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Scala tags/keywords

branch, branch, int, int, leaf, leaf, list, none, option, pair, some, string, tree, tree

The Scala patterns.scala source code

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] = None
    var found = false
    while (it.hasNext && !found) {
      val Pair(x1, y) = it.next
      if (x == x1) { found = true; result = Some(y) }
    }
    result
  }

  def printFinds[a](xs: List[Pair[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(Pair(3, "three"), Pair(4, "four")), 4)
  }
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala patterns.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.