Skip to content

Instantly share code, notes, and snippets.

@ivn-cote
Forked from Avaq/combinators.js
Created February 11, 2016 12:23
Show Gist options
  • Save ivn-cote/c42e3e52c7ddf61a0c9b to your computer and use it in GitHub Desktop.
Save ivn-cote/c42e3e52c7ddf61a0c9b to your computer and use it in GitHub Desktop.
Combinators
const I = x => x;
const K = x => _ => x;
const A = f => x => f(x);
const T = x => f => f(x);
const W = f => x => f(x)(x);
const C = f => y => x => f(x)(y);
const B = f => g => x => f(g(x));
const S = f => g => x => f(x)(g(x));
const P = f => g => x => y => f(g(x))(g(y));
const Y = f => (g => g(g))(g => f(x => g(g)(x)));
Name # Haskell Ramda Signature
identity I id identity a → a
constant K const always a → b → a
apply A ($) call (a → b) → a → b
thrush T (&) a → (a → b) → b
duplication W (a → a → b) → a → b
flip C flip flip (a → b → c) → b → a → c
compose B (.) compose (b → c) → (a → b) → a → c
substitution S (a → b → c) → (a → b) → a → c
psi P on (b → b → c) → (a → b) → a → a → c
fix-point Y fix (a → a) → a
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 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