ben lowery

The beginning (of the end?)

Mar 2 2007

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));
  }
}

Related posts:

  1. Monday the 4th
  2. Dojo’s little gems
  3. Pumping Messages (or A Blast From The Past)
  4. Monday the 7th
  5. WTF: assertFalse(/foo/.test(null)) fails?

Leave a Reply