Created
April 5, 2023 03:23
-
-
Save coder054/3cfc13a8dbe6b1399775945e024ecb33 to your computer and use it in GitHub Desktop.
The 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
const Y = (fn) => ((g) => g(g))((g) => fn((x) => g(g)(x))) | |
const factorialGenerator = (f) => (n) => n === 0 ? 1 : n * f(n - 1) | |
const factorial = Y(factorialGenerator) | |
factorial(5) // 120 | |
const sumFromZeroToNGenerator = (f) => (n) => n <= 1 ? n : n + f(n - 1) | |
const sumFromZeroToN = Y(sumFromZeroToNGenerator) | |
sumFromZeroToN(5) // 15 | |
const fibonaciGenerator = (f) => (n) => n < 2 ? 1 : f(n - 2) + f(n - 1) | |
const fibonaci = Y(fibonaciGenerator) | |
fibonaci(7) // 21 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment