public static <T, U, R> Function<U, R> partial(BiFunction<T, U, R> f, T x) {
return (y) -> f.apply(x, y);
}
In the expression above, I can understand that function partial returns another function, Function<U, R>
. That Function<U, R>
itself returns a value of R. What does the rest static <T, U, R>
stand for? I mean if Function<U, R>
returns an R what is the deal with <T, U, R>
?
Currying: A function returning another function that might return another function, but every returned function must take only one parameter at a time. Partial application: A function returning another function that might return another function, but each returned function can take several parameters.
Java still has a long way to go, but they made functional programming in Java easier. For example, we can now do simple partial application. This Java version is more limited than the Clojure one. It can only take a two argument function, whereas Clojure's supports arbitrarily many arguments.
Partial Application: The process of applying a function to some of its arguments. The partially applied function gets returned for later use. In other words, a function that takes a function with multiple parameters and returns a function with fewer parameters.
Partial application results in a function of smaller arity; in the example above, f has an arity of 3 while partial only has an arity of 2. More importantly, a partially applied function would return the result right away upon being invoke, not another function down the currying chain.
(I know it's not technically correct in Java terminology, but I'm going to say "argument" below where I mean "formal parameter" because mixing "formal parameter" and "type parameter" everywhere is confusing.)
T
is the type parameter for the x
argument.
partial
accepts two arguments:
f
, a function that accepts a T
and a U
and returns an R
:BiFunction<T, U, R> f
x
, which is of type T
:T x
partial
returns a new function that only accepts a U
(not a T
and a U
) and returns R
. Instead of expecting a T
argument, the new function uses the x
provided to partial
when calling f
.
In short: It returns a new function in which the first argument (of type T
) has been partially-applied (curried) via partial
's x
argument.
The reason we have <T, U, R>
near the beginning of the declaration is that that's how Java syntax lets us specify that partial
is a generic method, using type parameters T
, U
, and R
(otherwise, they look like type names, not type parameters).
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