Skip to content

Instantly share code, notes, and snippets.

@Avaq
Last active April 23, 2020 18:36
Show Gist options
  • Save Avaq/4003b3a1ad86d3efee295ebea62ba9b2 to your computer and use it in GitHub Desktop.
Save Avaq/4003b3a1ad86d3efee295ebea62ba9b2 to your computer and use it in GitHub Desktop.
Combinatory Fun
const ifElse = f => g => h => x => f(x) ? g(x) : h(x);
const isZero = a => a < 1;
const mult = a => b => a * b;
const dec = a => a - 1;
const factorial = Y(B(ifElse(isZero)(K(1)))(B(S(mult))(C(B)(dec))));
factorial(4);
const S = f => g => x => f(x)(g(x))
const K = x => y => x
const I = S(K)(K)
const B = S(K(S))(K)
const C = S(S(K(B))(S))(K(K))
const A = S(K(I))
const T = C(A)
const W = S(S)(K(I))
const head = xs => xs[0];
const tail = xs => xs.slice(1);
const add = a => b => a + b;
const dot = Y(f => n => n < 1 ? '' : '.' + f(n - 1));
const factorial = Y(f => n => n < 1 ? 1 : n * f(n - 1));
const reduce = f => Y(g => y => xs => xs.length < 1 ? y : g(f(y)(head(xs)))(tail(xs)));
dot(3) //> "..."
factorial(4) //> 24
reduce(add)(0)([1, 2, 3]) //> 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment