Skip to content

Instantly share code, notes, and snippets.

@mfix22
Last active October 19, 2017 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfix22/3208813b324d82a9ebd197e4b1c3bae8 to your computer and use it in GitHub Desktop.
Save mfix22/3208813b324d82a9ebd197e4b1c3bae8 to your computer and use it in GitHub Desktop.
Y-Combinator in modern JavaScript
// Y-Combinator implemented in JavaScript
// Inspired (mostly copied) from http://kestas.kuliukas.com/YCombinatorExplained/
// Thank you!
const Y = g =>
(f => f(f))(f =>
g(x => f(f)(x)))
const factorial = given =>
n => n < 2
? 1
: n * given(n - 1)
// Y(factorial)(5) => 120
@mfix22
Copy link
Author

mfix22 commented Oct 19, 2017

Follow up with multiple args:

const Y = g =>
  (f => f(f))(f =>
    g((...args) =>
      f(f)(...args)))

const isPrime = given => (n, s = 2) => n === s
  ? true
  : (n % s !== 0) && given(n, ++s)

console.log(Y(isPrime)(2));   // -> true
console.log(Y(isPrime)(17));  // -> true
console.log(Y(isPrime)(24));  // -> false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment