6

I was reading about currying in functional-programming, and I have a very basic 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 increment function, did I actually curry add ?

user2434
  • 6,339
  • 18
  • 63
  • 87
  • I had no idea what currying was, so I had to look it up. Thought I would share the Wikipedia article on [Currying](http://en.wikipedia.org/wiki/Currying) – Ascalonian Mar 19 '15 at 18:02
  • Related Post: [Does java support Currying?](http://stackoverflow.com/questions/6134278/does-java-support-currying) – Ascalonian Mar 19 '15 at 18:03

2 Answers2

7

You have partially applied add. This is related to currying.

In some languages that support partial application, functions are curried by default. you might be able write code like:

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

A curried function allows you to partially apply that function directly. Java doesn't support that kind of thing without extra machinery.

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 #2: I was wrong! I've corrected/modified my answer. As sepp2k pointed out this is only partial function application. The two concepts are related and often confused. In my defense there's a section on the currying Wikipedia page about the mixup.

Holger
  • 285,553
  • 42
  • 434
  • 765
axblount
  • 2,639
  • 23
  • 27
  • 1
    `increment` is not the result of currying `add` - it's the result of partially applying `add`. The result of currying `add` would be a function that can be called as `curriedAdd(arg1)(arg2)`. – sepp2k Mar 19 '15 at 20:34
  • 1
    [Flex your PECS](http://stackoverflow.com/questions/2723397/java-generics-what-is-pecs)! For full flexibility, the parameter of your `curry` method should instead be declared as a `BiFunction super T, ? super U, ? extends R>`. – jub0bs Nov 27 '15 at 21:52
0

No, you just call it. You need to pass function as argument, and return partial evaluation of that function to call it currying.

Zielu
  • 8,312
  • 4
  • 28
  • 41