Skip to content

Instantly share code, notes, and snippets.

@dwickstrom
Forked from Avaq/combinators.js
Last active June 13, 2018 12:13
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 dwickstrom/b8b6e46bff1111097945a68de4b9762f to your computer and use it in GitHub Desktop.
Save dwickstrom/b8b6e46bff1111097945a68de4b9762f to your computer and use it in GitHub Desktop.
Common combinators in JavaScript
const I = x => x;
const K = x => y => 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 # Birds Haskell Ramda Sanctuary Signature
identity I Idiot id identity I a → a
constant K Kestrel const always K a → b → a
apply A ($) call A (a → b) → a → b
thrush T Thrush (&) applyTo T a → (a → b) → b
duplication W Warble join² unnest² join² (a → a → b) → a → b
flip C Cardinal flip flip flip (a → b → c) → b → a → c
compose B Bluebird (.), fmap² map² compose, map² (b → c) → (a → b) → a → c
substitution S Starling ap² ap² ap² (a → b → c) → (a → b) → a → c
psi P on on (b → b → c) → (a → b) → a → a → c
fix-point¹ Y fix (a → a) → a

¹) In JavaScript and other non-lazy languages, it is impossible to implement the Y-combinator. Instead a variant known as the applicative or strict fix-point combinator is implemented. This variant is sometimes rererred to as the Z-combinator.

²) Algebras like ap have different implementations for different types. They work like Function combinators only for Function inputs.

Note that when I use the word "combinator" in this context, it implies "function combinator in the untyped lambda calculus".

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