-
Notifications
You must be signed in to change notification settings - Fork 71
Partial application
MarioAriasC edited this page Oct 24, 2014
·
4 revisions
We use partial application when we want to "fix" some parameters of a given function, resulting in new functions
import org.funktionale.partials.*
//use explicit typing for clarity sake
val prefixAndPostfix: (String, String, String) -> String = {(prefix:String, x:String,postfix:String) -> "${prefix}${x}${postfix}"}
val prefixAndBang: (String, String) -> String = prefixAndPostfix.partially3("!")
val hello: (String) -> String = prefixAndBang.partially1("Hello, ")
assertEquals(hello("funKTionale"),"Hello, funKTionale!")
Although partiallyX
is explicit probably you want something more natural. funKTionale comes with several overloads for the invoke
function that let you create partially applied functions in a more natural way using named parameters
import org.funktionale.partials.*
//use explicit typing for clarity sake
val prefixAndPostfix: (String, String, String) -> String = {(prefix:String, x:String,postfix:String) -> "${prefix}${x}${postfix}"}
//passing just the third parameter will return a new function (String, String) -> String
val prefixAndBang: (String, String) -> String = prefixAndPostfix(p3 = "!")
//passing just the first parameter will return a new function (String) -> String
val hello: (String) -> String = prefixAndBang(p1 = "Hello, ")
assertEquals(hello("funKTionale"),"Hello, funKTionale!")