Skip to content

Instantly share code, notes, and snippets.

@ChillyBwoy
Created May 4, 2017 14:14
Show Gist options
  • Save ChillyBwoy/0e075060d35fec0a8d76b4ca4fcf81b4 to your computer and use it in GitHub Desktop.
Save ChillyBwoy/0e075060d35fec0a8d76b4ca4fcf81b4 to your computer and use it in GitHub Desktop.
Y
const Y = h => (f => f(f))(f => h(n => f(f)(n)));
/* by steps */
// helpers
const recur = (f) => f(f);
const wrap = h => recur(f => h(n => f(f)(n)));
const fact0 = (n) => n < 2
? 1
: n * fact0(n - 1);
const fact1 = (f => n => n < 2
? 1
: n * f(f)(n - 1))
(f => n => n < 2
? 1
: n * f(f)(n - 1));
const fact2 = recur(f => n => n < 2
? 1
: n * f(f)(n - 1));
const fact3 = recur(f => {
const g = n => f(f)(n);
return n => n < 2
? 1
: n * g(n - 1);
});
const fact4 = wrap(g => n => n < 2
? 1
: n * g(n - 1));
const fact5 = Y(g => n => n < 2
? 1
: n * g(n - 1));
/* test */
const values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(values.map(fact0));
console.log(values.map(fact1));
console.log(values.map(fact2));
console.log(values.map(fact3));
console.log(values.map(fact4));
console.log(values.map(fact5));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment