Skip to content

Instantly share code, notes, and snippets.

@fronx
Last active January 4, 2016 08:19
Show Gist options
  • Save fronx/8595080 to your computer and use it in GitHub Desktop.
Save fronx/8595080 to your computer and use it in GitHub Desktop.
// This technique is very old. It's based on Church pairs.
// http://en.wikipedia.org/wiki/Church_encoding#Church_pairs
cons = function (a, b) {
return function (f) {
return f(a, b);
}
}
first = function (a, b) {
return a;
}
second = function (a, b) {
return b;
}
head = function (list) {
return list(first);
}
tail = function (list) {
return list(second);
}
list = cons(4, cons(3, cons(2,1)));
console.log(head(list)); // => 4
console.log(head(tail(list))); // => 3
console.log(head(tail(tail(list)))); // => 2
console.log(tail(tail(tail(list)))); // => 1
//--------------------------------------------------------
// head and tail are compatible with other list-like
// functions as well.
//
// example: the infinite list of natural numbers.
console.log("infinite list: natural numbers");
nat = (function _nat (n) {
return function (f) {
return f(n, _nat(n+ 1));
};
})(1);
console.log(head(nat)); // => 1
console.log(head(tail(nat))); // => 2
console.log(head(tail(tail(nat)))); // => 3
console.log(head(tail(tail(tail(nat))))); // => 4
console.log(head(tail(tail(tail(tail(nat)))))); // => 5
// …
@fronx
Copy link
Author

fronx commented Jan 24, 2014

@janv
Copy link

janv commented Jan 24, 2014

My brain hurts

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