Created
April 24, 2015 09:42
-
-
Save clojj/e8121744618641633db3 to your computer and use it in GitHub Desktop.
Java 8 partial functions... see https://www.pgrs.net/2015/04/23/partial-function-application-in-java-8/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+pgrs+%28Paul+Gross%27s+Blog%29
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@FunctionalInterface | |
interface TriFunction<T, U, V, R> { | |
R apply(T a, U b, V c); | |
} | |
public class Example { | |
public static int add(int x, int y) { | |
return x + y; | |
} | |
public static int add3(int x, int y, int z) { | |
return x + y + z; | |
} | |
public static <T, U, R> Function<U, R> partial(BiFunction<T, U, R> f, T x) { | |
return (y) -> f.apply(x, y); | |
} | |
public static <T, U, V, R> Function<V, R> partial(TriFunction<T, U, V, R> f, T x, U y) { | |
return (z) -> f.apply(x, y, z); | |
} | |
public static <T, U, V, R> BiFunction<U, V, R> partial(TriFunction<T, U, V, R> f, T x) { | |
return (y, z) -> f.apply(x, y, z); | |
} | |
public static void main(String[] args) { | |
Function adder = partial(Example::add, 5); | |
System.out.println(adder.apply(1)); // 6 | |
BiFunction<Integer, Integer, Integer> minus = (x, y) -> x - y; | |
Function subtractor = partial(minus, 10); | |
System.out.println(subtractor.apply(4)); // 6 | |
Function adder3 = partial(Example::add3, 1, 2); | |
System.out.println(adder3.apply(3)); // 6 | |
BiFunction adder3_2 = partial(Example::add3, 1); | |
System.out.println(adder3_2.apply(2, 3)); // 6 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment