10.柯里化函数以及偏函数

柯里化函数

定义:数学上的一种概念
简单说就是多元函数变换一元函数调用链

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)
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容