Skip to content

Instantly share code, notes, and snippets.

@dvanhorn
Last active August 29, 2015 14:18
Show Gist options
  • Save dvanhorn/5daa3f5e739f096a550e to your computer and use it in GitHub Desktop.
Save dvanhorn/5daa3f5e739f096a550e to your computer and use it in GitHub Desktop.
defun interp in Java (sketch)
// This is how I would structure this file:
// https://github.com/luisggpina/defunctionalized-CPS-interpreter/blob/master/src/c/lambda/Interpreter.java
// It ends up looking very much like the ML code you'd write
// using the visitor pattern to achieve pattern matching.
// This is just typed on the fly so it's probably got some
// trivial bugs in it.
interface Exp {
<A> A visit(ExpVisitor<A> v);
}
interface ExpVisitor<A> {
A var(String x);
A num(Integer n);
A app(Exp e1, Exp e2);
A lam(String x, Exp e);
}
interface ValVisitor<A> {
A clos(String x, Exp e, Env r);
A num(Integer n);
}
// The eval "function"
class Eval implements ExpVisitor<Value> {
Env r;
Eval(Env r) {
this.r = r;
}
Value var(String x) { return r.lookup(x); }
Value num(Integer n) { return new IntValue(n); }
Value app(Exp e1, Exp e2) {
return e1.visit(this).visit(new App(e2.visit(this)));
}
Value lam(String x, Exp e) {
return new Clos(x, e, this.r);
}
}
// The apply "function"
class App implements ValVisitor<Value> {
Value a;
App(Value a) {
this.a = a;
}
Value num(Integer n) { throw new TypeErrorException(); }
Value clos(String x, Exp e, Env r) {
return e.visit(new Eval(r.extend(x, this.a)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment