Created
August 22, 2012 20:26
-
-
Save belden/3429055 to your computer and use it in GitHub Desktop.
y-combinator.js
This file contains hidden or 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
// 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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My big references for y-combinators are:
http://stackoverflow.com/questions/93526/what-is-a-y-combinator
and two of the linked articles:
http://mvanier.livejournal.com/2897.html
http://www.mail-archive.com/[email protected]/msg02716.html