Skip to content

Instantly share code, notes, and snippets.

@belden
Created August 22, 2012 20:26
Show Gist options
  • Save belden/3429055 to your computer and use it in GitHub Desktop.
Save belden/3429055 to your computer and use it in GitHub Desktop.
y-combinator.js
// Here's a simple lambda combinator; it'll turn the function passed in
// into a function which, when called, returns a recursible copy of itself.
function y_combinator(curried) {
return function(f1){
return curried(function () { f1(f1)(arguments) });
}(function (f2) {
return curried(function () { f2(f2)(arguments) });
});
}
// Here's a use of that lambda combinator. We'll just print all the numbers
// in this list.
var numbers = [1, 2, 3];
y_combinator(function (recurse) {
return function () {
var number = numbers.shift();
console.log("number: " + number);
if (numbers.length) {
return recurse();
} else {
return;
}
}
})();
// a more incorrect application of the y-combinator(), I'm sure: try to short-circuit
// async.waterfall.
//
// Here's our actual list of tasks
var tasks = [f1, f2, f3, f4];
// a manager "task" which will stop executing tasks if one sets short_circuit.
var short_circuitable = [y_combinator(function(continue) {
return function () {
var task = tasks.shift();
if (short_circuit) {
return; // perhaps: return function () {}
// depending on async.waterfall's mechanism
// for knowing "no more work, yo!"
} else {
return continue();
}
}
})];
// let 'er rip
async.waterfall(short_circuitable);
// standard syntax errors are in effect.
@belden
Copy link
Author

belden commented Aug 22, 2012

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