Skip to content

Instantly share code, notes, and snippets.

@alandipert
Forked from anonymous/pantless.js
Created March 1, 2010 10:04
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 alandipert/318250 to your computer and use it in GitHub Desktop.
Save alandipert/318250 to your computer and use it in GitHub Desktop.
load(["lib/underscore.js"]);
load(["lib/json2.js"]);
var fact = ['def', 'fact', ['fn', ['n'],
['if', ['<=', 'n', 2],
'n',
['*', 'n', ['fact', ['-', 'n', 1]]]]]]
var infix = ['+', '-', '*', '/', '<', '>', '<=', '>='];
var forms = {
'quote': function(body) {
return JSON.stringify(body);
},
'cond': function() {
return _.map(_.partition(arguments, 2), function(pair) {
return compile(pair[0]) + " ? " + compile(pair[1]) + " : \n";
}).join('') + "null";
},
'def': function(name, body) {
return name + " = " + compile(body) + ";";
},
'fn': function(arglist, body) {
return "function("+arglist.join(",")+") {\n return " + compile(body) + ";\n}";
},
'if': function(test, if_true, if_false) {
return compile(test) + " ? " + compile(if_true) + " : " + compile(if_false);
}
};
function compile(exp) {
if(_.isArray(exp)) {
var first = _.first(exp);
var rest = _.rest(exp);
if(_.include(infix, first)) {
return _.map(rest, compile).join(first);
} else if(_.include(_.keys(forms), first)) {
return forms[first].apply(this, rest);
} else {
return first + "(" + _.map(rest, compile).join(',') + ")";
}
} else {
return exp;
}
}
print(JSON.stringify(fact));
print(compile(fact));
eval(compile(fact));
print(fact(5)) //120
/*["def","fact",["fn",["n"],["if",["<=","n",2],"n",["*","n",["fact",["-","n",1]]]]]]*/
/*fact = function(n) {*/
/*return n<=2 ? n : n*fact(n-1);*/
/*};*/
/*120*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment