Skip to content

Instantly share code, notes, and snippets.

@coder054
Created April 5, 2023 03:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coder054/3cfc13a8dbe6b1399775945e024ecb33 to your computer and use it in GitHub Desktop.
Save coder054/3cfc13a8dbe6b1399775945e024ecb33 to your computer and use it in GitHub Desktop.
The Y combinator
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