scala中的partia function是一个trait,其的类型为partialfunction[a,b],其中接收一个类型为a的参数,返回一个类型为b的结果。
例如:
val pf: partialfunction[int, string] = { case 1 => "one" case 2 => "two" case 3 => "three" case _ => "other" } println(pf(1)) //one println(pf(2)) //two println(pf(3)) //three println(pf(4)) //other
偏函数内部有一些方法,比如isdefinedat、orelse、 andthen、applyorelse等等。
isdefinedatisdefinedat : 这个函数的作用是判断传入来的参数是否在这个偏函数所处理的范围内。
刚才定义的pf来尝试使用isdefinedat(),只要是数字都是正确的,因为有case _=>"other"这一句。如果换成其他类型就会报错。
val pf: partialfunction[int, string] = { case 1 => "one" case 2 => "two" case 3 => "three" case _ => "other" } println(pf.isdefinedat(1)) //true println(pf.isdefinedat(2)) //true println(pf.isdefinedat(3)) //true println(pf.isdefinedat(4)) //true println(pf.isdefinedat("1")) /** * 类型不匹配 * type mismatch; * found : string("1") * required: int * println(pf.isdefinedat("1")) */
orelseorelse : 将多个偏函数组合起来使用,效果类似case语句。
val onepf: partialfunction[int, string] = { case 1 => "one" } val twopf: partialfunction[int, string] = { case 2 => "two" } val threepf: partialfunction[int, string] = { case 3 => "three" } val otherpf: partialfunction[int, string] = { case _ => "other" } val newpf = onepf orelse twopf orelse threepf orelse otherpf println(newpf(1)) //one println(newpf(2)) //two println(newpf(3)) //three println(newpf(4)) //other
这样,newpf跟原先的pf效果是一样的。
andthenandthen: 相当于方法的连续调用,比如g(f(x))。
pf1的结果返回类型必须和pf2的参数传入类型必须一致,否则会报错。
val pf1: partialfunction[int, string] = { case i if i == 1 => "one" } val pf2: partialfunction[string, string] = { case str if str eq "one" => "the num is 1" } val num = pf1 andthen pf2 println(num(1)) //the num is 1
applyorelseapplyorelse:它接收2个参数,第一个是调用的参数,第二个是个回调函数。如果第一个调用的参数匹配,返回匹配的值,否则调用回调函数。
val pf: partialfunction[int, string] = { case 1 => "one" } println(pf.applyorelse(1, { num: int => "two" })) //one println(pf.applyorelse(2, { num: int => "two" })) //two
偏应用函数偏应用函数(partial applied function)也叫部分应用函数,跟偏函数(partial function)从英文名来看只有一字之差,但他们二者之间却有天壤之别。
部分应用函数, 是指一个函数有n个参数, 而我们为其提供少于n个参数, 那就得到了一个部分应用函数。
举个例子,定义好一个函数有3个参数,再提供几个有1-2个已知参数的偏应用函数
def add(x: int, y: int, z: int) = x + y + z // x 已知 def addx = add(1, _: int, _: int) println(addx(2, 3)) //6 println(addx(3, 4)) //8 // x 和 y 已知 def addxandy = add(10, 100, _: int) println(addxandy(1)) //111 // z 已知 def addz = add(_: int, _: int, 10) println(addz(1, 2)) //13
以上就是java与scala中的偏函数与偏应用函数的使用方法的详细内容。
