Skip to content

Instantly share code, notes, and snippets.

@ikr
Last active July 27, 2018 07:49
Show Gist options
  • Save ikr/f7f98163025349191ffe9f76de77a5cf to your computer and use it in GitHub Desktop.
Save ikr/f7f98163025349191ffe9f76de77a5cf to your computer and use it in GitHub Desktop.
ADT / sum types in Java demo inspired by Philip Wadler's “Category Theory for the Working Hacker” talk
import java.util.function.Function;
interface Either<A, B> {
public <C> C caseExpr(Function<A, C> f, Function<B, C> g);
}
class Left<A, B> implements Either<A, B> {
private A x;
public Left(A x) {
this.x = x;
}
public <C> C caseExpr(Function<A, C> f, Function<B, C> g) {
return f.apply(x);
}
}
class Right<A, B> implements Either<A, B> {
private B y;
public Right(B y) {
this.y = y;
}
public <C> C caseExpr(Function<A, C> f, Function<B, C> g) {
return g.apply(y);
}
}
public class SumTypes {
private static Either<String, Integer> divide(int what, int byWhat) {
return byWhat == 0 ? new Left<>("Division by zero :(") : new Right<>(what / byWhat);
}
public static void main(String[] args) {
System.out.println(divide(196418, 10946).caseExpr(Function.identity(), x -> x.toString()));
System.out.println(divide(-13, 0).caseExpr(Function.identity(), x -> x.toString()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment