Skip to content

Instantly share code, notes, and snippets.

@colingourlay
Last active October 26, 2016 06:00
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 colingourlay/782b1bbacb915b9b923bffe3be3d5bbb to your computer and use it in GitHub Desktop.
Save colingourlay/782b1bbacb915b9b923bffe3be3d5bbb to your computer and use it in GitHub Desktop.
Using the Y combinator to immutably apply a series of operations to a value, using outputs as inputs. A "Function Centipede", if you will.
const Y = f => (x => x(x))(x => f(y => x(x)(y)));
const manufacture = Y(f => x => x.length > 1 ? f([x[1](x[0])].concat(x.slice(2))) : x[0]);
const stage = x => y => manufacture([y].concat(x));
const operations = [
x => x + 1,
x => x * 3,
x => x - 2
];
const transform = stage(operations);
transform(1); // 4
transform(2); // 7
manufacture([2].concat(operations)); // 7
// Same as `transform(2)` example above, avoiding any assignment
(x => y => (f => (x => x(x))(x => f(y => x(x)(y))))
(f => x => x.length > 1 ? f([x[1](x[0])].concat(x.slice(2))) : x[0])
([y].concat(x))
)
([
x => x + 1,
x => x * 3,
x => x - 2
])
(2); // 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment