Skip to content

Instantly share code, notes, and snippets.

@michaelavila
Last active August 29, 2015 14:26
Show Gist options
  • Save michaelavila/96586b3b14f7b0897031 to your computer and use it in GitHub Desktop.
Save michaelavila/96586b3b14f7b0897031 to your computer and use it in GitHub Desktop.
package com.michaelavila;
import java.util.Optional;
import java.util.function.Function;
class Either<A,B> {
private A left = null;
private B right = null;
private Either(A a, B b) {
left = a;
right = b;
}
public static <A,B> Either<A,B> left(A a) {
return new Either<A,B>(a, null);
}
public static <A,B> Either<A,B> right(B b) {
return new Either<A,B>(null, b);
}
public static <B> Either<String,B> fromOptional(Optional<B> o) {
Optional<Either<String,B>> rs = o.map((B b) -> Either.right(b));
return rs.orElse(Either.left("Missing value"));
}
public <U> Either<A,U> map(Function<? super B,? extends U> mapper) {
return right == null ? Either.left(left) : Either.right(mapper.apply(right));
}
public <U> Either<A,U> flatMap(Function<? super B,? extends Either<A,U>> mapper) {
return right == null ? Either.left(left) : mapper.apply(right);
}
@Override
public String toString() {
return String.format("Either<%s,%s>", left, right);
}
}
public class FunctionalExamples {
public static void main(String[] args) {
Function<Integer, Function<Integer,Integer>> triple = m -> n -> {
return m*n*3;
};
Function<Integer, Either<String, Integer>> isGreaterThanTen = n -> {
return n > 10 ? Either.right(n) : Either.left("Value must be greater than 10");
};
Function<Integer, Either<String, Integer>> isLessThanTwenty = n -> {
return n < 20 ? Either.right(n) : Either.left("Value must be less than 20");
};
Either<String,Integer> arg1 = Either.fromOptional(Optional.of(11))
.flatMap(isLessThanTwenty)
.flatMap(isGreaterThanTen);
Either<String,Integer> arg2 = Either.fromOptional(Optional.of(19))
.flatMap(isLessThanTwenty)
.flatMap(isGreaterThanTen);
Either<String,Integer> arg3 = Either.fromOptional(Optional.of(39))
.flatMap(isLessThanTwenty)
.flatMap(isGreaterThanTen);
Either<String,Integer> arg4 = Either.fromOptional(Optional.empty());
Either<String,Integer> result = arg1.map(triple).flatMap(arg2::map);
System.out.println(result); // Either<null,627>
result = arg1.map(triple).flatMap(arg3::map);
System.out.println(result); // Either<Value must be less than 20,null>
result = arg1.map(triple).flatMap(arg4::map);
System.out.println(result); // Either<Missing value,null>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment