Skip to content

Instantly share code, notes, and snippets.

@polux
Created January 11, 2014 19:19
Show Gist options
  • Save polux/8375474 to your computer and use it in GitHub Desktop.
Save polux/8375474 to your computer and use it in GitHub Desktop.
Staged Interpreter
class None {
None();
}
class Some {
final value;
Some(this.value);
}
/* environments */
class ConsEnv {
final x;
final value;
final tail;
ConsEnv(this.x, this.value, this.tail);
insert(x, v) => new ConsEnv(x, v, this);
lookup(x) => (x == this.x) ? new Some(this.value) : this.tail.lookup(x);
}
class NilEnv {
NilEnv();
insert(x, v) => new ConsEnv(x, v, this);
lookup(x) => new None();
}
/* AST + interpreter */
class Lit {
final value;
Lit(this.value);
eval(env) => lift(this.value);
}
class Var {
final x;
Var(this.x);
eval(env) => env.lookup(this.x).value;
}
class Lambda {
final x;
final t;
Lambda(this.x, this.t);
eval(env) => <(y) => ~this.t.eval(env.insert(this.x, <y>))>;
}
class App {
final t1;
final t2;
App(this.t1, this.t2);
eval(env) => <(~this.t1.eval(env))(~this.t2.eval(env))>;
}
main() {
final f = new Lambda("x", new Lambda("y", new Var("x")));
final e = new App(new App(f, new Lit(42)), new Lit(43));
print(e.eval(new NilEnv()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment