Skip to content

Instantly share code, notes, and snippets.

@laser
Created July 18, 2018 03:00
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 laser/1aaa14f7aa1ba5b7017bf997776fbe6d to your computer and use it in GitHub Desktop.
Save laser/1aaa14f7aa1ba5b7017bf997776fbe6d to your computer and use it in GitHub Desktop.
pattern matching Java
public abstract class Tree {
// Constructor private so the type is sealed.
private Tree() {}
public abstract <T> T match(Function<Empty, T> a,
Function<Leaf, T> b,
Function<Node, T> c);
public static final class Empty extends Tree {
public <T> T match(Function<Empty, T> a,
Funciton<Leaf, T> b,
Function<Node, T> c) {
return a.apply(this);
}
public Empty() {}
}
public static final class Leaf extends Tree {
public final int n;
public <T> T match(Function<Empty, T> a,
Function<Leaf, T> b,
Function<Node, T> c) {
return b.apply(this);
}
public Leaf(int n) { this.n = n; }
}
public static final class Node extends Tree {
public final Tree left;
public final Tree right;
public <T> T match(Function<Empty, T> a,
Function<Leaf, T> b,
Function<Node, T> c) {
return c.apply(this);
}
public Node(Tree left, Tree right) {
this.left = left; this.right = right;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment