-
-
Save Lewiscowles1986/c76218cb89da48de75dce70cbc548a42 to your computer and use it in GitHub Desktop.
JavaScript implementation of cons, car and cdr
This file contains 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
/** | |
* 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