Skip to content

Instantly share code, notes, and snippets.

@ayago
Last active July 26, 2019 02:36
Show Gist options
  • Save ayago/b0b565bef9bce98253f6ab90804e5056 to your computer and use it in GitHub Desktop.
Save ayago/b0b565bef9bce98253f6ab90804e5056 to your computer and use it in GitHub Desktop.
Currying in Java
import java.util.function.Function;
import static java.lang.String.format;
class SampleCurrying {
public static void main(String[] args) {
Fx2<Integer, Integer, Integer> add = (x, y) -> x + y;
System.out.println(format("Non curried add function of 2 arity result: %s", add.apply(2, 3)));
Function<Integer, Function<Integer, Integer>> curriedAdd = Currying.curry(add);
System.out.println(format("Add function curried with value 2 then 3: %s", curriedAdd.apply(2).apply(3)));
Fx3<Integer, Integer, String, String> descriptiveAdd = (x, y, z) -> z + (x + y);
Function<Integer, Function<Integer, Function<String, String>>> curriedDescriptiveAdd =
Currying.curry(descriptiveAdd);
Function<String, String> describe5 = curriedDescriptiveAdd
.apply(2)
.apply(3);
System.out.println(describe5.apply("The result is: "));
}
/**
* Function with arity of 2
* @param <I1> type of first input
* @param <I2> type of second input
* @param <O> type of output
*/
@FunctionalInterface
public interface Fx2<I1, I2, O> {
/**
* Execute this function
* @param inputOne first input
* @param inputTwo second input
* @return output of this function
*/
O apply(I1 inputOne, I2 inputTwo);
}
/**
* Function with arity of 3
* @param <I1> type of first input
* @param <I2> type of second input
* @param <I3> type of third input
* @param <O> type of output
*/
@FunctionalInterface
public interface Fx3<I1, I2, I3, O> {
/**
* Execute this function
* @param inputOne first input
* @param inputTwo second input
* @param inputThree third input
* @return output of this function
*/
O apply(I1 inputOne, I2 inputTwo, I3 inputThree);
}
public static class Currying {
public static <I1, I2, I3, O> Function<I1, Function<I2, Function<I3, O>>> curry(Fx3<I1, I2, I3, O> f){
return i1 -> i2 -> i3 -> f.apply(i1, i2, i3);
}
public static <I1, I2, O> Function<I1, Function<I2, O>> curry(Fx2<I1, I2, O> f){
return i1 -> i2 -> f.apply(i1, i2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment