Created
September 24, 2012 00:23
-
-
Save diiq/3773552 to your computer and use it in GitHub Desktop.
It's a lisp in js.
This file contains 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
Array.prototype.map = function(func) { | |
var ret = []; | |
for (var i = 0; i < this.length; i++) | |
ret[i] = func(this[i]); | |
return ret; | |
} | |
var lisp = function() { | |
var builtin = { | |
cns: function(args) { | |
return [eval(args[0]), eval(args[1])]; | |
}, | |
car: function(args) { | |
return eval(args[0])[0]; | |
}, | |
cdr: function(args) { | |
return eval(args[0])[1]; | |
}, | |
quo: function(args) { | |
return args[0]; | |
}, | |
eq: function(args) { | |
return eval(args[0]) === eval(args[1]); | |
}, | |
cnd: function(args) { | |
if (eval(args[0])) return eval(args[1]); | |
return eval(args[2]); | |
}, | |
fun: function(args) { | |
return { | |
fun: true, | |
args: args[0], | |
code: args.slice(1, args.length) | |
}; | |
} | |
}; | |
var names = [{}]; | |
var eval = function(ast) { | |
var f, args, i, ret; | |
if (!Array.isArray(ast) || ast.length === 0) return names[0][ast] || ast; | |
f = ast.shift(); | |
f = Array.isArray(f) ? eval(f) : f; | |
if (builtin.hasOwnProperty(f)) return builtin[f](ast); | |
if (f.fun) { | |
n = {} | |
args = ast.map(eval); | |
for (i = 0; i < f.args.length; i++) | |
n[f.args[i]] = eval(args[i]); | |
names.unshift(n); | |
ret = f.code.map(eval).pop(); | |
names.shift(); | |
return ret; | |
} | |
} | |
return eval; | |
}(); | |
lisp(["car", [["fun", ["a"], ["cns", "a", ["quo", "c"]]], ["quo", "d"]]])==="d"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment