Skip to content

Instantly share code, notes, and snippets.

@Rafailong
Created December 10, 2015 04:44
Show Gist options
  • Save Rafailong/17e4fb6afc36265e670e to your computer and use it in GitHub Desktop.
Save Rafailong/17e4fb6afc36265e670e to your computer and use it in GitHub Desktop.
Y-Combinator
var Y = require('./y');
function factorial(proc) {
return function (n) {
return n === 0 ? 1 : (n * proc(n - 1));
}
}
var fact = Y(factorial);
var r = fact(3);
console.log(r);
function findMax(proc) {
return function (array) {
if (array.length < 1) return 0;
var element = array[0];
return Math.max(element, proc(array.splice(1)));
}
}
var max = Y(findMax);
var r = max([0, 5, -3, -2, -1]);
log(r);
function log(x) {
console.log(x);
}
function Y(outer) {
function inner(proc) {
function apply(arg) {
return proc(proc)(arg);
}
return outer(apply);
}
return inner(inner);
}
module.exports = Y;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment