Scala 函數式編程_偏函數_Partial Functionsjava
偏函數是隻對函數定義域的一個子集進行定義的函數。 scala中用scala.PartialFunction[-T, +S] 類來表示。編程
好比,對給定的輸入參數類型,偏函數只能接受該類型的某些特定的值。一個定義爲(Int) => String 的偏函數可能不能接受全部Int值爲輸入。app
以下定義一個偏函數,這個函數只會接收 1 和 2 ,這兩個輸入。其餘輸入會報錯。函數式編程
val one: PartialFunction[Int, String] = { case 1 => "one" case 2 => "two" } println(one.isDefinedAt(1)) println(one.isDefinedAt(2)) println(one(1)) println(one(2))
運行並輸出,函數
truespa
truescala
onecode
twothree
isDefinedAt表示 這個參數是否在函數的定義域中,不然拋出異常。io
以下,
...........
...........
false
scala.MatchError: 3 (of class java.lang.Integer)
at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:253)
at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:251)
再來看一個例子,
val signal: PartialFunction[Int, Int] = { case x if x > 1 => 1 case x if x < -1 => -1 } println(signal(1212)) println(signal(-74567)) println(signal(0))
運行並輸出,
C:\WorkSpace6-scala\scala-train\src\com\usoft>scala PartialFunction.scala
1
-1
scala.MatchError: 0 (of class java.lang.Integer)
at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:253)
使用 orElse 組合函數
val one: PartialFunction[Int, String] = { case 1 => "one" } val two: PartialFunction[Int, String] = { case 2 => "two" } val three: PartialFunction[Int, String] = { case 3 => "three" } val wildcard: PartialFunction[Int, String] = { case _ => "something else" } val partial = one orElse two orElse three orElse wildcard println(partial.isDefinedAt(4)) println(partial(4))
運行並輸出,
C:\WorkSpace6-scala\scala-train\src\com\usoft>scala PartialFunction.scala
true
something else
=============END=============