Created
March 21, 2023 09:56
-
-
Save imtrinity94/9cca4e04753435483ecb976d424771c3 to your computer and use it in GitHub Desktop.
The Y-combinator: a utility function
This file contains 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
// The Y-combinator: a utility function! | |
var Y = function Y(hof) { | |
return function (x) { | |
return x(x); | |
}(function (x) { | |
return hof(function (y) { | |
return x(x)(y); | |
}); | |
}); | |
}; | |
console.log([1, 2, 3, 4, 5].map( | |
// Wrap the higher-order function in the Y-combinator | |
// "factorial" is not a function's name: it's introduced as a parameter | |
Y(function (factorial) { | |
return function (n) { | |
return n <= 1 ? 1 : factorial(n - 1) * n; | |
}; | |
}))); | |
// [ 1, 2, 6, 24, 120 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: This method allocates a new closure for every iteration, which may significantly increase memory usage. It's only here to demonstrate the possibility, but should be avoided in production. Use a temporary variable or a named function expression instead.
https://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator