Skip to content

Instantly share code, notes, and snippets.

@mike-neck
Last active August 29, 2015 14:24
Show Gist options
  • Save mike-neck/d270b214d07bce399c74 to your computer and use it in GitHub Desktop.
Save mike-neck/d270b214d07bce399c74 to your computer and use it in GitHub Desktop.
import java.util.function.Function;
/**
* 関数インターフェースでペアを表現する。
*
*/
public class FunctionalPair {
public static void main(String[] args) {
Pair<Integer, String> status = Pair.of(200, "OK");
System.out.println(status.first()); //200
System.out.println(status.second()); //"OK"
}
//ジェネリクスで A or B の表現ができないので Object をバインドしている
@FunctionalInterface
interface Pair<A, B> extends
Function<Function<A, Function<B, Object>>, Object> {
static <A, B> Pair<A, B> of(A a, B b) {
return f -> f.apply(a).apply(b);
}
default A first() {
return (A) apply(a -> b -> a);
}
default B second() {
return (B) apply(a -> b -> b);
}
}
}
import java.util.function.Supplier;
// かなり脆弱なMaybe
public interface Maybe<T> extends Supplier<T> {
static <V> Maybe<V> empty() {
return () -> {throw new NoSuchElementException()};
}
static <T> Maybe<V> just(V v) {
return () -> v;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment