Skip to content

Instantly share code, notes, and snippets.

@forax
Created March 19, 2017 15:36
Show Gist options
  • Save forax/885d8181267d92aa012e98327a63c305 to your computer and use it in GitHub Desktop.
Save forax/885d8181267d92aa012e98327a63c305 to your computer and use it in GitHub Desktop.
class Morphism {
/*
List = Cons(int value, List next) | Nil
*/
interface ListVisitor<R, P> {
R Cons(int value, ListAcceptor next, P param);
R Nil(P param);
}
interface ListAcceptor {
<R, P> R accept(P param, ListVisitor<R, P> visitor);
}
private static void test2() {
//List list = new Cons(3, new Cons(2, new Nil()));
ListAcceptor list = new ListAcceptor() {
public <R, P> R accept(P param, ListVisitor<R,P> visitor) {
return visitor.Cons(3, new ListAcceptor() {
public <S, Q> S accept(Q param, Morphisms.ListVisitor<S,Q> visitor) {
return visitor.Cons(2, new ListAcceptor() {
public <T, U> T accept(U param, ListVisitor<T, U> visitor) {
return visitor.Nil(param);
}
}, param);
}
}, param);
}
};
//int v = Cons(value, next)-> value + rec(next)
// | Nil -> 0
int v = list.accept(null, new ListVisitor<Integer, Void>() {
public Integer Cons(int value, ListAcceptor next, Void param) { return value + next.accept(param, this); }
public Integer Nil(Void __) { return 0; }
});
System.out.println(v);
}
public static void main(String[] args) {
test2();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment