Skip to content

Instantly share code, notes, and snippets.

@tomchentw
Last active May 23, 2016 01:57
Show Gist options
  • Save tomchentw/b529529cd1c5f433695453846e676477 to your computer and use it in GitHub Desktop.
Save tomchentw/b529529cd1c5f433695453846e676477 to your computer and use it in GitHub Desktop.
YCombinator
const genFib = f => n => {
if (n <= 1) return 1;
return f(n - 1) + f(n - 2);
};
const fib = someFunc(genFib);
/*
* Above fib is the result we want. But we don't know HOW to implement someFunc
*/
// From Line 6, we know someFunc is a function that will return fib, with a parameter genFib passed in
// So, a naive implementation of someFunc would be the following (let's assume "fib" is defined at this point)
const fib = (f => f(fib))(genLib);
//
const fib = (f => genLib(n => fib(n)))(genLib); // substitute f inside the function with its real value: genLib
//
const fib = (f => genLib(n => someFunc(genLib)(n)))(genLib); // we don't have fib before defining this line, so substitute fib as well
// We get:
const someFunc = f => genLib(n => someFunc(genLib)(n)); // we now have a version of someFunc that don't rely on fib to be defined
//
const someFunc = f => f(n => someFunc(f)(n)); // genLib is f, so someFunc don't rely on genLib as well
// Then,
const yComb = f => f(n => yComb(f)(n));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment