Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional Programming Beginner : Currying in Java

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 ?

like image 498
user2434 Avatar asked Mar 19 '15 17:03

user2434


People also ask

Is currying functional programming?

Currying is only one concept of functional programming. There are other concepts like pure functions and higher-order functions (which include currying) that may interest you.

What is a currying function explain with an example?

Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript: function add (a, b) { return a + b; } add(3, 4); // returns 7. This is a function that takes two arguments, a and b, and returns their sum.

Is Java good for functional programming?

Java is a functional style language and the language like Haskell is a purely functional programming language. Let's understand a few concepts in functional programming: Higher-order functions: In functional programming, functions are to be considered as first-class citizens.


1 Answers

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.

like image 195
axblount Avatar answered Sep 27 '22 22:09

axblount