Functional Programming Beginner: Currying in Java

I read about currying in functional programming, and I have a very simple question:

If I have two functions in Java

int add(int x, int y){ return x+y; } 

and I create another method

  int increment(int y){ return add(1, y); } 

In the above code, when I wrote the increment function, did I really do curry add ?

+5
source share
2 answers

You partially applied add . This is due to currying.

In some languages ​​that support a partial application, functions have a default value. you can write code, for example:

 increment = add(1) println(increment(2)) # => 3 

The curried function allows you to partially apply this function directly. Java does not support such things without additional mechanisms.

EDIT:

In Java 8 with lambdas and java.util.function you can define a curry function.

 import java.util.function.Function; public class Example { public static <T, U, R> Function<T, Function<U, R>> curry(BiFunction<T, U, R> f) { return t -> u -> f.apply(t, u); } public static int add(int x, int y) { return x + y; } public static void main(String[] args) { Function<Integer, Function<Integer, Integer>> curriedAdd = curry(Example::add); // or // BiFunction<Integer, Integer, Integer> add = (x, y) -> x + y; // curriedAdd = curry(add); Function<Integer, Integer> increment = curriedAdd.apply(1); System.out.println(increment.apply(4)); } } 

EDIT No. 2: I was wrong! I corrected / changed my answer. As sepp2k pointed out, this is only a partial function application. These two concepts are related and often confused. My defense has a section on the Wikipedia page about mixing.

+6
source

No, you just call it. You need to pass the function as an argument and return a partial evaluation of this function in order to call it currying.

0
source

Source: https://habr.com/ru/post/1215703/


All Articles