Created
January 14, 2015 08:06
-
-
Save rtoal/f9ceca258902444d785e to your computer and use it in GitHub Desktop.
A warmup exercise for a class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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