henix / blog

some notes
0 stars 0 forks source link

Scala 的 Partial Function 和 partially applied functions #6

Closed henix closed 10 years ago

henix commented 11 years ago

Partial Function

定义在部分元素上的 function http://www.scala-lang.org/api/current/index.html#scala.PartialFunction

trait PartialFunction[-A, +B] extends (A) => B {
  abstract def apply(v: A): B
  abstract isDefinedAt(x: A): Boolean // 多了个 isDefinedAt
}

应用:

value match {
  case Some(value) => ???
  case None => ???
}

map.foreach { case (k, v) ⇒ println(k + " -> " + v) }

List.collect { case i: Int => i + 1}

http://blog.bruchez.name/2011/10/scala-partial-functions-without-phd.html

partially applied functions

即 currying

val add = (a: Int, b: Int) => a + b
val inc = add(_: Int, 1)
inc(10) // returns 11