Skip to content

Instantly share code, notes, and snippets.

@friedbrice
Last active May 16, 2017 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save friedbrice/10d63d36814f42ecab4351458e747e4f to your computer and use it in GitHub Desktop.
Save friedbrice/10d63d36814f42ecab4351458e747e4f to your computer and use it in GitHub Desktop.
Either.java
import java.util.Optional;
import java.util.function.Function;
public abstract class Either<L, R> {
public static <L0, R0> Either<L0, R0> left(L0 value) {
return new Left<L0, R0>(value);
}
public static <L0, R0> Either<L0, R0> right(R0 value) {
return new Right<L0, R0>(value);
}
public abstract <T0> T0 fold(Function<L, T0> ifLeft, Function<R, T0> ifRight);
public final Optional<L> getLeft() {
return fold(
(L l) -> Optional.of(l),
(R r) -> Optional.empty()
);
}
public final <T0> Either<T0, R> mapLeft(Function<L, T0> f) {
return fold(
(L l) -> Either.left(f.apply(l)),
(R r) -> Either.right(r)
);
}
public final <T0> Either<T0, R> flatMapLeft(Function<L, Either<T0, R>> k) {
return fold(
(L l) -> k.apply(l),
(R r) -> Either.right(r)
);
}
public final Optional<R> getRight() {
return fold(
(L l) -> Optional.empty(),
(R r) -> Optional.of(r)
);
}
public final <T0> Either<L, T0> mapRight(Function<R, T0> f) {
return fold(
(L l) -> Either.left(l),
(R r) -> Either.right(f.apply(r))
);
}
public final <T0> Either<L, T0> flatMapRight(Function<R, Either<L, T0>> k) {
return fold(
(L l) -> Either.left(l),
(R r) -> k.apply(r)
);
}
private final static class Left<L0, R0> extends Either<L0, R0> {
L0 value;
Left(L0 value) {
this.value = value;
}
@Override
public <T0> T0 fold(Function<L0, T0> ifLeft, Function<R0, T0> ifRight) {
return ifLeft.apply(this.value);
}
}
private final static class Right<L0, R0> extends Either<L0, R0> {
R0 value;
Right(R0 value) {
this.value = value;
}
@Override
public <T0> T0 fold(Function<L0, T0> ifLeft, Function<R0, T0> ifRight) {
return ifRight.apply(this.value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment