Skip to content

Instantly share code, notes, and snippets.

@dglittle
Created June 9, 2018 22:24
Show Gist options
  • Save dglittle/944f4f33f5ce58ffaf507fddaad20548 to your computer and use it in GitHub Desktop.
Save dglittle/944f4f33f5ce58ffaf507fddaad20548 to your computer and use it in GitHub Desktop.
var code = '["do", ["set", "x", 0], ["while", ["<", ["get", "x"], 10], ["set", "x", ["+", ["get", "x"], 1]]]]'
function parse_lisp(x) {
return JSON.parse(x)
}
console.log('hi')
var lisp_variables = {}
function exec_lisp(parse_tree) {
if (typeof(parse_tree) == 'object') {
if (parse_tree[0] == 'if') {
if (exec_lisp(parse_tree[1])) {
return exec_lisp(parse_tree[2])
} else {
return exec_lisp(parse_tree[3])
}
}
if (parse_tree[0] == 'while') {
while (exec_lisp(parse_tree[1])) {
exec_lisp(parse_tree[2])
}
return
}
var flattened_array = []
for (var i = 0; i < parse_tree.length; i++) {
flattened_array.push(exec_lisp(parse_tree[i]))
}
if (flattened_array[0] == '+') {
return flattened_array[1] + flattened_array[2]
} else if (flattened_array[0] == '*') {
return flattened_array[1] * flattened_array[2]
} else if (flattened_array[0] == '<') {
return flattened_array[1] < flattened_array[2]
} else if (flattened_array[0] == 'set') {
lisp_variables[flattened_array[1]] = flattened_array[2]
} else if (flattened_array[0] == 'get') {
return lisp_variables[flattened_array[1]]
} else if (flattened_array[0] == 'do') {
}
} else {
return parse_tree
}
}
var parsed = parse_lisp(code)
console.log(parsed)
console.log(exec_lisp(parsed))
console.log('lisp_variables = ', lisp_variables)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment