Skip to content

Instantly share code, notes, and snippets.

@jdan
Created December 14, 2016 19:10
Show Gist options
  • Save jdan/398ca9005b22fc79848b9f110cf04719 to your computer and use it in GitHub Desktop.
Save jdan/398ca9005b22fc79848b9f110cf04719 to your computer and use it in GitHub Desktop.
const K = x => ls => [x].concat(ls)
const add = ([fst, snd, ...rest]) => [fst + snd].concat(rest)
const mult = ([fst, snd, ...rest]) => [fst * snd].concat(rest)
const dup = ([fst, ...rest]) => [fst].concat([fst, ...rest])
const swp = ([fst, snd, ...rest]) => [snd, fst, ...rest]
const print = ([fst, ...rest]) => {
console.log(fst)
return rest
}
// compose(f, g, h)(x) => f(g(h(x)))
const compose = (...fns) => x => fns
.reverse()
.reduce((acc, fn) => fn(acc), x)
// 1 2 swp 3 dup add mult add print
//
// could compile into the following:
const stack = [K(1), K(2), swp, K(3), dup, add, mult, add, print].reverse()
compose(...stack)([])
// => "8"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment