Kotlin 柯里化(Currying)-函数调用链和偏函数

柯里化(Currying)的概念:

简单说就是多元函数参数变换成一系列单函数参数调用链

Currying的实现方法:

无返回值的函数

fun sum(x: Int, y: Int, z: Int) = x + y + z

sum(1, 2, 3)

如果我们把它按照柯里化的思路重新设计,那么最终就可以实现链式调用:

fun sum(x: Int) = { y: Int ->

    { z: Int -> x + y + z }

}

sum(1)(2)(3)

原函数:

fun hello(x:String,y:Int,z:Double):Boolean{

return true

}

currying函数:

fun hell(x:String)
=fun (y:Int)
=fun (z:Double)
=true

fun log(tag: String) =fun(target: OutputStream) =fun(message: Any?) = target.write("[$tag] $message\n".toByteArray())

//currying 扩展函数
fun<P1,P2,P3,R> Function3<P1,P2,P3,R>.curried()
        =fun(p1:P1)=fun(p2:P2)=fun(p3:P3)=this(p1,p2,p3)

/**定义一个匿名函数
 * 两个参数byteArry,charset
 * 返回String类型
 */
val makeString = fun(byteArry: ByteArray,charset: Charset):String{
    return String(byteArry,charset)
}

/**
 * 定义一个变量
 * partial2是一个偏函数
 * 第二个参数charset已经绑定为GBK
 */
val makeStringFromGbKBytes = makeString.partial2(charset("GBK"))

/**
 * 定义一个扩展偏函数方法
 * 参数是P1、P2
 * 返回值是:R
 * 参数p2已经被偏函数绑定
 * fun()只需要传第一参数就好了
 * partial1和partial2都是绑定参数的
 */
fun <P1,P2,R> Function2<P1,P2,R>.partial2(p2: P2) = fun(p1:P1) = this(p1,p2)
fun <P1,P2,R> Function2<P1,P2,R>.partial1(p1: P1) = fun(p2:P2) = this(p1,p2)
 

fun main(args: Array<String>) {
 

    //偏函数
    //1.定义一个变量
    //2.先柯里化一下它,对于固定每次都要传的参数,可以先固定一下它
    //3.对于多参数函数,通过先指定它的一些固定的参数值剩下一个参数值不固定,得到的依然是一个函数,这个函数就是原来函数的偏函数
    val consoleLogWithTag = (::log.curried())("benny")(System.out)
    consoleLogWithTag("Hello wang dong")
    consoleLogWithTag("helllo boy")
    consoleLogWithTag("hello girl")
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值