Skip to content

Instantly share code, notes, and snippets.

@Lewiscowles1986
Forked from scotthaleen/ConsCarCdr.js
Last active September 19, 2023 07:54
Show Gist options
  • Save Lewiscowles1986/c76218cb89da48de75dce70cbc548a42 to your computer and use it in GitHub Desktop.
Save Lewiscowles1986/c76218cb89da48de75dce70cbc548a42 to your computer and use it in GitHub Desktop.
JavaScript implementation of cons, car and cdr
/**
* Generic Container, which can contain a single item, and the next item as a function
*/
function cons(value, next) {
return function wrap(wrapper) { return wrapper(value, next) };
};
/**
* Get value of item by calling unwrap function, taking value
*/
function car(unwrap) {
return unwrap(function(value, next) { return value });
};
/**
* Get value of next by calling unwrap function, taking next
*/
function cdr(unwrap) {
return unwrap(function(value, next) { return next });
};
var list = cons(1, cons(2, null));
// Why are they not using console.log?
document.writeln( car(list));
document.writeln( car(cdr(list)));
document.writeln( cdr(cdr(list)));
document.writeln( car(cdr(cdr(list))));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment