Skip to content

Instantly share code, notes, and snippets.

@rtoal
Created January 14, 2015 08:06
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 rtoal/f9ceca258902444d785e to your computer and use it in GitHub Desktop.
Save rtoal/f9ceca258902444d785e to your computer and use it in GitHub Desktop.
A warmup exercise for a class
C.evalAST = function (ast) {
var environment = {}
function ev(ast) {
return !Array.isArray(ast) ? ast : ops[ast[0]].apply(undefined, ast.slice(1))
}
var ops = {
id : function(x) {return environment.hasOwnProperty(x) ? environment[x] : 0},
set : function(id, exp) {return environment[id] = ev(exp)},
'+' : function(x, y) {return ev(x) + ev(y)},
'-' : function(x, y) {return ev(x) - ev(y)},
'*' : function(x, y) {return ev(x) * ev(y)},
'/' : function(x, y) {return ev(x) / ev(y)},
'^' : function(x, y) {return Math.pow(ev(x), ev(y))},
seq : function(e1, e2) {ev(e1); return ev(e2)}
}
return ev(ast)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment