Woo boy. Some fun javascript for your consideration. Who said scheme was dead? This code adapted from the Abelson and Sussman lectures on the Structure and Interpretation of Programs.
function cons(x,y) { var f = function(pick) { if(pick == 0) return x; else if(pick == 1) return y; } f.toString = _printCons; return f; } function _printCons() { var s = ""; s += (car(this) || "(nil)"); if(cdr(this)) { s += "," s += cdr(this); } return s; } function car(p) { return p(0); } function cdr(p) { return p(1); } // cons(1, cons(2, cons(3, cons(4,null)))); function list() { var l = null; for(var i = arguments.length-1; i >= 0; i--) l = cons(arguments[i],l); return l; } function map(p,l) { if(l == null) return null; else { return cons( p(car(l)), map(p, cdr(l)) ); } } function for_each(p,l) { if(l == null) return "done"; else { p(car(l)); for_each(p, cdr(l)); } }
Advertisements