Functional Programming With Java 简明教程

Functional Programming with Java - Currying

柯里化是一种技术,用它将多参数函数调用替换为多个带有较少参数的方法调用。

Currying is a technique where a many arguments function call is replaced with multiple method calls with lesser arguments.

请参阅以下等式。

See the below equation.

(1 + 2 + 3) = 1 + (2 + 3) = 1 + 5 = 6

在函数中:

In terms of functions:

f(1,2,3) = g(1) + h(2 + 3) = 1 + 5 = 6

这种函数级联称为柯里化,对级联函数的调用必须产生与调用主函数相同的结果。

This cascading of functions is called currying and calls to cascaded functions must gives the same result as by calling the main function.

以下示例演示了柯里化的工作原理。

Following example shows how Currying works.

import java.util.function.Function;

public class FunctionTester {
   public static void main(String[] args) {
      Function<Integer, Function<Integer, Function<Integer, Integer>>>
         addNumbers = u -> v -> w -> u + v + w;
      int result = addNumbers.apply(2).apply(3).apply(4);
      System.out.println(result);
   }
}

Output

9