部分函数
部分应用函数(Partial Applied Function)是缺少部分参数的函数,是一个逻辑上概念。
例如:def sum(x: Int, y: Int, z: Int) = x + y + z,
当调用sum的时候,如果不提供所有的参数,或者只提供某些参数时,比如sum _ , sum(3, _: Int, :Int), sum(: Int, 3, 4), 这样就生成了所谓的部分应用函数。
案例:
def showMsg(title:String, content:String, num:Int)={
println(title+": "+content+": "+num+"米")
}
showMsg("警告","当前水位是",12)
//部分函数形式
val title = "警告"
def showWaterAlter = showMsg(title,_:String,_:Int) //部分函数
showWaterAlter("当前水位",14)
偏函数
在Scala中,偏函数是具有类型PartialFunction[-T,+V]的一种函数。T是其接受的函数类型,V是其返回的结果类型。
偏函数最大的特点就是它只接受和处理其参数定义域的一个子集,而对于这个子集之外的参数则抛出运行时异常。这与Case语句的特性非常契合,因为我们在使用case语句是,常常是匹配一组具体的模式,最后用“_”来代表剩余的模式。如果一一组case语句没有涵盖所有的情况,那么这组case语句就可以被看做是一个偏函数。
案例一:
//偏函数
def funPartional:PartialFunction[String, Int]={
case "hello" => 1
case "world" => 2
case _ => 0
}
val num = funPartional("scala")
println(num) // 0
//批量输入,判断输出
val worlds = List("hello","world","gree","kb09")
//方式一
val ints:List[Int] = worlds.collect(funPartional)
println(ints) // List(1, 2, 0, 0)
ints.foreach(println) // 1 2 0 0
//方式二
worlds.collect(funPartional).foreach(println) // 1 2 0 0
//方式三
worlds collect funPartional foreach println // 1 2 0 0
案例二:
//输入字符,输出元组
def funTupple:PartialFunction[Char,(Char,Int)]={
case 'A' => ('A',1)
case 'B' => ('B',1)
case _ => ('X',1)
}
val tuple:(Char,Int) = funTupple('A')
println(tuple) // (A,1)
var chars = List('A','B','C','D')
val tuples:List[(Char,Int)] = chars.collect(funTupple)
//方式一
tuples.foreach(println) // (A,1),(B,1),(X,1),(X,1)
//方式二
tuples.foreach(x => {println(x._1,x._2)}) // (A,1),(B,1),(X,1),(X,1)
案例三:
//输入不同类型数据,输出Int类型
def fun2:PartialFunction[Any,Int]={
case i:Int => i
case _ => 0
}
var list = List("a","c",2,2.5,4,6)
list.collect(fun2).foreach(println) // 0 0 2 0 4 6