Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created February 14, 2011 18:43
Show Gist options
  • Select an option

  • Save rwaldron/826328 to your computer and use it in GitHub Desktop.

Select an option

Save rwaldron/826328 to your computer and use it in GitHub Desktop.
Exercise to understand Lisp cons/car/cdr, by implementing in JS
<script src="cons.js"></script>
//cons, car and cdr
(function( global ) {
var Cons = {
cons: function() {
var ret = [],
args = [].slice.call( arguments, 0 ),
len = args.length,
idx, arg;
for ( idx = 0; idx < len; idx++ ) {
var arg = args[ idx ];
ret = ret.concat( arg );
}
return ret;
},
// These need to be broken out and abstracted for DRYer code
car: function() {
var car = this.cons.apply( null, [].slice.call( arguments, 0 ) );
return car.splice( 0, 1 );
},
cdr: function() {
var cdr = this.cons.apply( null, [].slice.call( arguments, 0 ) );
return cdr.splice( 1, cdr.length );
}
};
global.cons = Cons.cons;
global.car = Cons.car;
global.cdr = Cons.cdr;
})( this );
//console.log(
// Actual,
// Expected
//);
console.log(
"cons",
cons( [ "foo", "bar", "baz", "qux" ] ),
[ "foo", "bar", "baz", "qux" ]
);
console.log(
"cons",
cons( [ "foo", "bar", "baz", "qux" ] , [ "alpha", "beta" ] ),
[ "foo", "bar", "baz", "qux", "alpha", "beta" ]
);
console.log(
"cons",
cons( ["foo"], cons( ["bar", "baz", "qux"], cons( ["alpha"] ), cons(["beta"]) ) ),
[ "foo", "bar", "baz", "qux", "alpha", "beta" ]
);
console.log(
"car",
car( [ "foo", "bar", "baz", "qux" ] ),
[ "foo" ]
);
console.log(
"cdr",
cdr( [ "foo", "bar", "baz", "qux" ] ),
[ "bar", "baz", "qux" ]
);
console.log(
"car(cdr())",
car( cdr( [ "foo", "bar", "baz", "qux" ] ) ),
[ "bar" ]
);
// Composites
function cadr( x ) {
return car( cdr( x ) );
}
console.log(
"cadr",
cadr( [ "foo", "bar", "baz", "qux" ] ),
[ "bar" ]
);
function caar( x ) {
return car( car( x ) );
}
console.log(
"caar",
caar( [ "foo", "bar", "baz", "qux" ] ),
[ "foo" ]
);
@db48x
Copy link

db48x commented Feb 16, 2011

cowboy: yes, good catch. Lisp of course hides the nil at the end of every list, but it is still there

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment