Last active
October 26, 2016 06:00
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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