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 ?

2
  • I had no idea what currying was, so I had to look it up. Thought I would share the Wikipedia article on Currying Commented Mar 19, 2015 at 18:02
  • Related Post: Does java support Currying? Commented Mar 19, 2015 at 18:03

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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).
Flex your PECS! For full flexibility, the parameter of your curry method should instead be declared as a BiFunction<? super T, ? super U, ? extends R>.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.