Created
September 11, 2018 13:32
-
-
Save Johnicholas/f0435c61b9f06f4dc4e975bcc193ee2e to your computer and use it in GitHub Desktop.
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
console.log(JSON.stringify(parser.parse("(first (list 1 (+ 2 3) 9))")) == JSON.stringify(["first",["list",1,["+",2,3],9]])); | |
let primitives = { | |
"first": (args) => { | |
if (args.length != 1) { | |
console.error("first called with unexpected number of arguments: ", args.length); | |
} | |
let the_arg = args[0]; | |
let the_first_of_the_arg = the_arg[0]; | |
return the_first_of_the_arg; | |
}, | |
"+": (args) => args.reduce((total, element) => total + element, 0), | |
"list": (args) => args | |
} | |
function my_eval(ast) { | |
switch (typeof ast) { | |
case "object": | |
// Note: we are assuming if it is an object, then it is an array. | |
let args = ast.map(my_eval); | |
let f = args.shift(); | |
return f(args); | |
case "string": | |
if (primitives[ast]) { | |
return primitives[ast]; | |
} else { | |
console.error("not recognized primitive: ", ast); | |
return null; | |
} | |
case "number": | |
return ast; | |
default: | |
console.error("unexpected type: ", typeof ast); | |
} | |
} | |
// want to see 3 | |
console.log(my_eval(["+", 1, 2]) == 3) | |
// want to see 6 | |
console.log(my_eval(["+", 1, 2, 3]) == 6) | |
// want to see [1, 5, 9] | |
console.log(JSON.stringify(my_eval(["list", 1, ["+", 2, 3], 9])) == JSON.stringify([1, 5, 9])) | |
// want to see 1 | |
console.log(my_eval(["first", ["list", 1, ["+", 2, 3], 9]]) == 1) | |
function run(it) { | |
return my_eval(parser.parse(it)); | |
} | |
console.log(JSON.stringify(run("(first (list 1 (+ 2 3) 9))")) == 1); | |
document.querySelector("button").addEventListener("click", (e) => { | |
document.querySelector("#output").innerText = run(document.querySelector("input").value); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment