Coursera Scala 4-6:模型匹配

Coursera Scala 4-6:模型匹配

匹配值

val times = 1

times match {
  case 1 => "one"
  case 2 => "two"
  case _ => "some other number"
}
 List(('a',1), ('b',2), ('a',1)) match {
        case Nil => println("null")
        case (C, n) :: ps => (C, n+1) :: ps   得到List(('a',2), ('b',2), ('a',1))
        case p :: ps => p            得到('a',1)
        case p :: ps => ps            得到List(('b',2), ('a',1))

      }
  }

匹配类型

def bigger(o: Any): Any = {
  o match {
    case i: Int if i < 0 => i - 1
    case i: Int => i + 1
    case d: Double if d < 0.0 => d - 0.1
    case d: Double => d + 0.1
    case text: String => text + "s"
  }
}

匹配类成员

def calcType(calc: Calculator) = calc match {
  case _ if calc.brand == "hp" && calc.model == "20B" => "financial"
  case _ if calc.brand == "hp" && calc.model == "48G" => "scientific"
  case _ if calc.brand == "hp" && calc.model == "30B" => "business"
  case _ => "unknown"
}

样本类Case Class

使用样本类可以方便得存储和匹配类的内容。你不用new关键字就可以创建它们

scala> case class Calculator(brand: String, model: String)
defined class Calculator

scala> val hp20b = Calculator("hp", "20b")
hp20b: Calculator = Calculator(hp,20b)

使用样本类进行模式匹配:

e match{
   case pattern => expr
}

在没有匹配项时抛出 MatchError

Pattern可以是:

  • 小写字母开头表示变量(保留字除外) 用于绑定值到这个变量
  • 大写开头表示常量 两者是否相等来进行匹配(==)

构造器pattern C(p1,....,pn) 匹配所有C类型(或子类型)通过p1...p构造的
(注意类的定义要用case class)
同样的变量只能在Pattern出现一次

顺序匹配下去

 trait Expr
 case class Number(n:Int) extends Expr
 case class Sum(e1:Expr,e2:Expr) extends Expr
 object exprs {
     def show(e:Expr): String = e match {
         case Number(x) => x.toString
         case Sum(l.r) => show(l)+"+"+show(r)
     }
 }
 show(Sum(Number(1),Number(44)))               > res0:String=1+44


例子:

  trait Expr {
  def isNumber: Boolean
  def isSum: Boolean
  def numValue: Int
  def leftOp: Expr
  def rightOp: Expr
  def show():String = this match{
      case Number(n) => n+""
      case Sum(e1,e2) => e1+"+"+e2
  }
}

另一个例子:

Scala代码
def show(e: Expr): String = e match {
   case Sum(Prod(x1, x2), Prod(x3, x4)) =>
     if (x1 == x3) show(x1) + "*" + "(" + show(x2) + "+" + show(x4) + ")"
     else if (x1 == x4) show(x1) + "*" + "(" + show(x2) + "+" + show(x3) + ")"
     else if (x2 == x3) show(x2) + "*" + "(" + show(x1) + "+" + show(x4) + ")"
     else if (x2 == x4) show(x2) + "*" + "(" + show(x1) + "+" + show(x3) + ")"
     else show(_Prod(x1, x2)) + "+" + show(_Prod(x3, x4))
   case Sum(n1, n2) => show(n1) + "+" + show(n2)
   case Prod(Sum(n1, n2), n3) => "(" + show(_Sum(n1, n2)) + ")" + "*" + show(n3)
   case Prod(n3, Sum(n1, n2)) => show(n3) + "*(" + show(_Sum(n1, n2)) + ")"
   case Prod(n1, n2) => show(n1) + "*" + show(n2)
   case _ => e.toString()
 }

Reference

http://twitter.github.io/scala_school/zh_cn/basics2.html#match
http://hongjiang.info/scala-pattern-matching-1/

时间: 2024-10-02 12:25:11

Coursera Scala 4-6:模型匹配的相关文章

Coursera Scala 5-3:Implicit

Coursera Scala 5-3:Implicit 归并排序 上一节课的排序函数不够通用,类型只适用Int: object mergesort{ def msort(xs: List[Int]):List[Int] = { val n = xs.length/2 if(n==0) xs else{ def merge(xs:List[Int],ys: List[Int]):List[Int] = (xs,ys)match { case (Nil,ys) => ys case (xs,Nil)

Coursera Scala 5-5 List:Reduction of Lists

Coursera Scala 5-5 List:Reduction of Lists 另一个list常用的操作是:连结集合元素.例如sum(list) ReduceLeft 使用ReduceLeft可以很方便的编写通用的连结方法 def sum(xs: List[Int]) = (0 :: xs) reduceLeft ((x,y) => x+y) def product(xs : List[Int]) = (1 :: xs) reduceLeft((x,y) => x*y) FoldLeft

Coursera Scala 5-2:Pairs和Tuple

Coursera Scala 5-2:Pairs和Tuple pair: (x,y) scala> val (label,value) = (1,"s") label: Int = 1 value: String = s scala> (1,"s") res0: (Int, String) = (1,s) 超过两个元素的就是tuple了 (T1,....,Tn)是Scala.Tuplen[T1,...,Tn]的缩写 (e1,....,en)是Scala.

Coursera Scala 5-4:List的高阶函数

Coursera Scala 5-4:List的高阶函数 Recurring Patterns for Computations on Lists 重复出现的Lists计算模式 lists的很多函数有相似的结构,重复出现的模式有: 用某个方法转换每个元素 用某个条件提取元素 用某种方法链接元素 函数式编程语言,让程序员能写出更通用的计算模式,通过使用高阶函数. Applying a Function to Elements of a List 将一个list的所有元素,进行转换.例子:返回一个新

Coursera Scala 4-1:函数作为对象

Coursera Scala 4-1:函数作为对象 Functions Types Relate to Classes Scala是纯粹的面向对象的语言,函数是拥有apply方法的对象. 函数类型A=>B等价于: package scala trait Function1[A,B]{ def apply(x:A):B } Functions Values Ralate to Objects 匿名函数 (x:Int) => x*x 等价于: { class AnonFun extends Fun

Coursera Scala 4-7:Lists

Coursera Scala 4-7:Lists Lists val nums = List(1,3,4) val empty = List() val fruit = List("apples","oranges") val diag3 = List(List(1,0,0),List(0,1,0),List(0,0,1)) immutable List是递归的,arrays则不是 The List Type 和arrays一样,lists的元素必须是相同类型的.

Coursera Scala 4-3:子类型和泛型

Coursera Scala 4-3:子类型和泛型 Type Bounds def assertAllPos[S <: IntSet](r: S): S = ... S <: T 表示S是T的子类 S >: T表示S是T的父类 也可以这么用: [S >: NonEmpty <: IntSet] 协变covariant 这个的意思是: 如果List是convariant的,S<:T (S是T的子类)成立,那么List[S]<:List[T]也成立 covariant

Coursera Scala 2-5,6:类

Coursera Scala 2-5,6:类 class Rational(n: Int, d: Int) { require(d != 0) private val g = gcd(n.abs, d.abs) //将构造器传入的参数,赋值成成员变量,外部才可以访问 val numer = n / g val denom = d / g def this(n: Int) = this(n, 1) def +(that: Rational): Rational = new Rational( nu

Coursera Scala 2-1:高阶函数

把函数当做参数,传递给函数(好绕-..-),称为高阶函数. 高阶函数使我们的代码保持DRY(Dont't Repeat Yourself) 举个例子 一个返回所有扩展名为".scala"的文件的方法: def filesHere = (new java.io.File(".")).listFiles def filesEnding(query: String) = for (file <- filesHere; if file.getName.endsWith