# 1. 偏函数

Scala中的Partia Function是一个Trait，其的类型为PartialFunction[A,B]，其中接收一个类型为A的参数，返回一个类型为B的结果。

``````
scala> val pf:PartialFunction[Int,String] = {
|   case 1=>"One"
|   case 2=>"Two"
|   case 3=>"Three"
|   case _=>"Other"
| }
pf: PartialFunction[Int,String] = <function1>

scala> pf(1)
res0: String = One

scala> pf(2)
res1: String = Two

scala> pf(3)
res2: String = Three

scala> pf(4)
res3: String = Other
``````

## 1.1 isDefinedAt

isDefinedAt : 这个函数的作用是判断传入来的参数是否在这个偏函数所处理的范围内。

``````scala> pf.isDefinedAt(1)
res4: Boolean = true

scala> pf.isDefinedAt(2)
res5: Boolean = true

scala> pf.isDefinedAt("1")
<console>:13: error: type mismatch;
found   : String("1")
required: Int
pf.isDefinedAt("1")
^

scala> pf.isDefinedAt(100)
res7: Boolean = true
``````

``````scala> val anotherPF:PartialFunction[Int,String] = {
|    case 1=>"One"
|    case 2=>"Two"
|    case 3=>"Three"
| }
anotherPF: PartialFunction[Int,String] = <function1>

scala> anotherPF.isDefinedAt(1)
res8: Boolean = true

scala> anotherPF.isDefinedAt(2)
res9: Boolean = true

scala> anotherPF.isDefinedAt(3)
res10: Boolean = true

scala> anotherPF.isDefinedAt(4)
res11: Boolean = false
``````

## 1.2 orElse

orElse : 将多个偏函数组合起来使用，效果类似case语句。

``````
scala> val onePF:PartialFunction[Int,String] = {
|   case 1=>"One"
| }
onePF: PartialFunction[Int,String] = <function1>

scala> val twoPF:PartialFunction[Int,String] = {
|   case 2=>"Two"
| }
twoPF: PartialFunction[Int,String] = <function1>

scala> val threePF:PartialFunction[Int,String] = {
|   case 3=>"Three"
| }
threePF: PartialFunction[Int,String] = <function1>

scala> val otherPF:PartialFunction[Int,String] = {
|   case _=>"Other"
| }
otherPF: PartialFunction[Int,String] = <function1>

scala> val newPF = onePF orElse twoPF orElse threePF orElse otherPF
newPF: PartialFunction[Int,String] = <function1>

scala> newPF(1)
res0: String = One

scala> newPF(2)
res1: String = Two

scala> newPF(3)
res2: String = Three

scala> newPF(4)
res3: String = Other
``````

## 1.3 andThen

andThen: 相当于方法的连续调用，比如g(f(x))。

``````scala> val pf1:PartialFunction[Int,String] = {
|   case i if i == 1 => "One"
| }
pf1: PartialFunction[Int,String] = <function1>

scala> val pf2:PartialFunction[String,String] = {
|   case str if str eq "One" => "The num is 1"
| }
pf2: PartialFunction[String,String] = <function1>

scala> val num = pf1 andThen pf2
num: PartialFunction[Int,String] = <function1>

scala> num(1)
res4: String = The num is 1
``````

pf1的结果返回类型必须和pf2的参数传入类型必须一致，否则会报错。

## 1.4 applyOrElse

applyOrElse：它接收2个参数，第一个是调用的参数，第二个是个回调函数。如果第一个调用的参数匹配，返回匹配的值，否则调用回调函数。

``````scala> onePF.applyOrElse(1,{num:Int=>"two"})
res5: String = One

scala> onePF.applyOrElse(2,{num:Int=>"two"})
res6: String = two
``````

# 2. 偏应用函数

``````scala> def add(x:Int,y:Int,z:Int) = x+y+z
add: (x: Int, y: Int, z: Int)Int

res1: Int = 6

res2: Int = 8

res3: Int = 111