Created
September 16, 2014 18:25
-
-
Save janickr/0a5e855654804b6edddc to your computer and use it in GitHub Desktop.
java 8, inspired by https://speakerdeck.com/raganwald/javascript-combinators
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
import java.util.List; | |
import java.util.function.BiFunction; | |
import java.util.function.Function; | |
import static java.util.Arrays.asList; | |
public class Combinators { | |
public static <A, B, R> BiFunction<B, A, R> flip(BiFunction<A, B, R> fn) { | |
return (a, b) -> fn.apply(b, a); | |
} | |
public static String arrow(String a, String b) { | |
return a + " -> " + b; | |
} | |
public static <A, B, R> Function<A, Function<B, R>> curry(BiFunction<A, B, R> fn) { | |
return (a) -> (b) -> fn.apply(a, b); | |
} | |
public static <A, B, R> BiFunction<A, B, R> uncurry(Function<A, Function<B, R>> fn) { | |
return (a, b) -> fn.apply(a).apply(b); | |
} | |
public static <T, R> List<R> map(List<T> mappable, Function<T, R> fn) { | |
return (List<R>) asList(mappable.stream().map(fn).toArray()); | |
} | |
public static <T, R> Function<List<T>, List<R>> mapWith(Function<T, R> mapper) { | |
BiFunction<Function<T, R>, List<T>, List<R>> flipped = flip(Combinators::map); | |
return curry(flipped).apply(mapper); | |
} | |
public static Integer times2(Integer i) { | |
return i * 2; | |
} | |
public static void main(String[] args) { | |
System.out.println(flip(Combinators::arrow).apply("x", "y")); | |
Function<String, Function<String, String>> curriedArrow = curry(Combinators::arrow); | |
System.out.println(curriedArrow.apply("finger").apply("moon")); | |
Function<String, String> pointer = curry(Combinators::arrow).apply("finger"); | |
System.out.println(pointer.apply("moon")); | |
Function<MyTestSubject, String> getter = MyTestSubject::getName; | |
System.out.println(map(asList(1, 2, 3), Combinators::times2)); | |
Function<List<Integer>, List<Integer>> doubleAll = mapWith(Combinators::times2); | |
System.out.println(doubleAll.apply(asList(1, 2, 3))); | |
Function<List<MyTestSubject>, List<String>> names = mapWith(MyTestSubject::getName); | |
System.out.println(names.apply(asList(new MyTestSubject("jef"), new MyTestSubject("marie")))); | |
} | |
private static class MyTestSubject { | |
private String name; | |
private MyTestSubject(String name) { | |
this.name = name; | |
} | |
public String getName() { | |
return name; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment