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
//Combinators
const I = x => x;
//Function composition
const compose = f => g => x => f(g(x));
//List manipulation
const head = xs => xs[0];
const tail = xs => xs.slice(1);
const append = x => xs => [...xs, x];
//Iteration
const foldl = f => y => xs => xs.length > 0 ? foldl(f)(f(y)(head(xs)))(tail(xs)) : y;
const foldr = f => y => xs => xs.length > 0 ? f(foldr(f)(y)(tail(xs)))(head(xs)) : y;
const map = f => foldl(y => x => append(f(x))(y))([]);
//Lib
const add = a => b => a + b;
const mult = a => b => a * b;
const pipe = foldr(compose)(I);
//Program
map(pipe([add(1), mult(2)]))([1, 2, 3]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment