English 中文(简体)
Currying
  • 时间:2024-12-22

Functional Programming with Java - Currying


Previous Page Next Page  

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 calpng the main function.

Following example shows how Currying works.

import java.util.function.Function;

pubpc class FunctionTester {
   pubpc 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
Advertisements