[转]Scan: Pattern Matching Anonymous Functions

原文:http://www.scala-lang.org/files/archive/spec/2.11/08-pattern-matching.html#pattern-matching-anonymous-functions

 

  BlockExpr ::= `{' CaseClauses `}'

An anonymous function can be defined by a sequence of cases

{ case p1 => b1 case pn => bn }

which appear as an expression without a prior match. The expected type of such an expression must in part be defined. It must be either scala.Functionk[S1,,Sk, R] for some k>0, orscala.PartialFunction[S1, R], where the argument type(s) S1,,Sk must be fully determined, but the result type R may be undetermined.

If the expected type is scala.Functionk[S1,,Sk, R], the expression is taken to be equivalent to the anonymous function:

(x1:S1,,xk:Sk) => (x1,,xk) match {
  case p1 => b1 case pn => bn
}

Here, each xi is a fresh name. As was shown here, this anonymous function is in turn equivalent to the following instance creation expression, where T is the weak least upper bound of the types of all bi.

new scala.Functionk[S1,,Sk, T] {
  def apply(x1:S1,,xk:Sk): T = (x1,,xk) match {
    case p1 => b1 case pn => bn
  }
}

If the expected type is scala.PartialFunction[S, R], the expression is taken to be equivalent to the following instance creation expression:

new scala.PartialFunction[S, T] {
  def apply(x: S): T = x match {
    case p1 => b1 case pn => bn
  }
  def isDefinedAt(x: S): Boolean = {
    case p1 => true case pn => true
    case _ => false
  }
}

Here, x is a fresh name and T is the weak least upper bound of the types of all bi. The final default case in the isDefinedAt method is omitted if one of the patterns p1,,pn is already a variable or wildcard pattern.

Example

Here is a method which uses a fold-left operation /: to compute the scalar product of two vectors:

def scalarProduct(xs: Array[Double], ys: Array[Double]) =
  (0.0 /: (xs zip ys)) {
    case (a, (b, c)) => a + b * c
  }

The case clauses in this code are equivalent to the following anonymous function:

(x, y) => (x, y) match {
  case (a, (b, c)) => a + b * c
}
posted @ 2014-12-04 16:15  Scan.  阅读(204)  评论(0)    收藏  举报