-
-
Save alandipert/318250 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
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