柯里化函数
定义:数学上的一种概念
简单说就是多元函数变换一元函数调用链
fun hello(x: String,y: Int):Boolean{
print("x==$x,y==$y \n")
return true
}
fun curriedHello(x: String):(y: Int) -> Boolean{
return fun (y):Boolean{
print("x==$x,y==$y \n")
return true
}
}
fun main() {
hello("a",123)
curriedHello("a")(123)
}
利用扩展函数对该类函数进行扩展
fun <P1, P2, R> Function2<P1, P2, R>.curried()
= fun(p1: P1) = fun(p2: P2) = this(p1, p2)
fun main() {
hello("a",123)
curriedHello("a")(123)
::hello.curried()("a")(123)
}
偏函数
1.偏函数是在柯里化的基础上得来
2.原函数传入部分参数后得到的新函数就叫偏函数
fun main() {
var printY=::hello.curried()("a")
printY(1)
printY(2)
}
网友评论