Since Kotlin supports many concepts from functional programming, I was wondering if there is a way to do partial application of a function in Kotlin as well?
One such example of where partial application can be useful is:
// 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)
}
Currying function in Kotlin Android 12.08. 2018 It allows transforming a given function that takes multiple arguments into a sequence of functions, each having a single argument. Each of the resulting functions handles one argument of the original (uncurried) function and returns another function.
In computer science, partial application (or partial function application) refers to the process of fixing a number of arguments to a function, producing another function of smaller arity. Given a function , we might fix (or 'bind') the first argument, producing a function of type .
You can supply one or more arguments to bind to your partially applied function, and you can partially apply a partially applied function as well.
Functional Programming in Kotlin is a reworked version of the bestselling Functional Programming in Scala, with all code samples, instructions, and exercises translated into the powerful Kotlin language. In this authoritative guide, you'll take on the challenge of learning functional programming from first principles.
Out of the box, no. But it isn't too hard to do with a helper function:
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
So partial2 takes a function of 2 arguments and the first argument and applies it to get a function of 1 argument. You would have to write such helpers for all arities you need.
Alternatively, you can do it with an extension method:
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)
There is a very nice and light library to Kotlin: org.funktionale
. In module funktionale-currying
you'll find extenstion methods to lambdas: curried()
and uncurried()
.
Example:
val add = { x: Int, y: Int -> x + y }.curried()
val add3 = add(3)
fun test() {
println(add3(5)) // prints 8
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With