Created
December 10, 2015 04:44
-
-
Save Rafailong/17e4fb6afc36265e670e to your computer and use it in GitHub Desktop.
Y-Combinator
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
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); | |
} |
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
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