Kotlin是否支持部分申请?

idu*_*olz 7 functional-programming partial-application kotlin

由于Kotlin支持函数式编程的许多概念,我想知道是否有办法在Kotlin中部分应用函数?

部分应用程序可能有用的一个这样的例子是:

// In one class
fun doSomething(cb: (a, b) -> Unit) {
    <some logic here to compute someField>
    doSomethingElse(cb.applyPartially(someField))
}

// In another class
fun doSomethingElse(cb: (b) -> Unit) {
    <some logic here to compute someOtherField>
    cb(someOtherField)
}
Run Code Online (Sandbox Code Playgroud)

tri*_*rNZ 7

开箱即用,没有.但是使用辅助函数并不难:

    fun add(a: Int, b:Int): Int {
        return a + b
    }

    fun <A, B, C> partial2(f: (A, B) -> C, a: A): (B) -> C {
        return { b: B -> f(a, b)}
    }

    val add1 = partial2(::add, 1)

    val result = add1(2) //3
Run Code Online (Sandbox Code Playgroud)

因此partial2采用2个参数和第一个参数的函数,并将其应用于获取1个参数的函数.你必须为你需要的所有灵魂编写这样的助手.

或者,您可以使用扩展方法执行此操作:

fun <A,B,C> Function2<A,B,C>.partial(a: A): (B) -> C {
    return {b -> invoke(a, b)}
}

val abc: (Int) -> Int = (::add).partial(1)
Run Code Online (Sandbox Code Playgroud)


Cil*_*ing 5

Kotlin 有一个非常漂亮且轻便的库:org.funktionale. 在模块中,funktionale-currying您将找到 lambdas:curried()和的扩展方法uncurried()

例子:

val add = { x: Int, y: Int -> x + y }.curried()
val add3 = add(3)

fun test() {
    println(add3(5)) // prints 8
}
Run Code Online (Sandbox Code Playgroud)

  • 小更新:该项目似乎已迁移到:https://arrow-kt.io (3认同)