返回顶部

收藏

Scala 模式匹配 (Case Classes)

更多

使用Case Classes进行模式匹配

patterns.scala

package examples

/** Illustrate the use of pattern matching in Scala. */
object patterns {

  /** We need an abstract base class for trees. Subclasses with 
   *  the 'case' modifier can be used in pattern matching expressions 
   *  to deconstruct trees. 
   */
  abstract class Tree
  case class Branch(left: Tree, right: Tree) extends Tree
  case class Leaf(x: Int) extends Tree

  /** Case classes have an implicit constructor methods which allows 
   *  to create objects withouth the 'new' keyword. It saves some typing 
   *  and makes code clearer. 
   */
  val tree1 = Branch(Branch(Leaf(1), Leaf(2)), Branch(Leaf(3), Leaf(4)))

  /** Return the sum of numbers found in leaves. 
   *  'match' is a generalization of 'switch' in C-like languages 
   * 
   *  Patterns consist of case class constructors (which can 
   *  be nested), and lower case variables which are 
   *  bound to the values with which the class has been constructed. 
   */
  def sumLeaves(t: Tree): Int = t match {
    case Branch(l, r) => sumLeaves(l) + sumLeaves(r)
    case Leaf(x) => x
  }

  /** This illustrates the use of Option types. Since the 
   *  method is not known in advance to find 'x', the 
   *  return type is an Option. Options have two possible 
   *  values, either 'Some' or 'None'. It is a type-safe 
   *  way around 'null' values. 
   */
  def find[A, B](it: Iterator[(A, B)], x: A): Option[B] = {
    var result: Option[B] = None
    while (it.hasNext && result == None) {
      val Pair(x1, y) = it.next
      if (x == x1) result = Some(y)
    }
    result
  }

  def printFinds[A](xs: List[(A, String)], x: A) =
    find(xs.elements, x) match {
      case Some(y) => println(y)
      case None => println("no match")
    }

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

标签:模式匹配,Scala

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. 四火 发表 2015-09-20 17:02:00 Scala的模式匹配
  2. importnewzz 发表 2015-10-16 10:30:44 Scala的模式匹配
  3. Freewind 发表 2013-01-01 09:03:09 10. 使用anorm操作数据库
  4. Freewind 发表 2013-05-09 02:19:58 Lift项目零散笔记
  5. 梦想家 发表 2013-08-20 06:34:11 scala HelloWorld
  6. Freewind 发表 2014-05-02 12:18:25 Scala类型系统之:来自星星的猫
  7. 博主 发表 2013-12-25 06:40:00 褪去Scala的糖衣(6) -- partial application
  8. hongjiang 发表 2014-06-01 16:32:03 华东地区scala爱好者聚会(2014上海)
  9. juvenxu 发表 2014-07-08 15:58:08 基于Cucumber和Scala的验收测试
  10. Freewind 发表 2011-09-13 13:50:00 解析一句信息量很大的代码
  11. Freewind 发表 2011-09-13 14:40:03 怎样实现 ‘aaa := "AAA",即为符号增加函数并隐式转换
  12. admin 发表 2014-08-22 05:51:19 Scala函数使用

发表评论