Search code examples
javalambdacurryingpartial-application

Java 8 partial function application /currying


 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> ?


Solution

  • (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).