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 ?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With