functional programming - Why does function composition compose from right to left in Javascript? -


function composition composes right left:

const comp  = f => g => x => f(g(x)); const inc = x => x + 1; const dec = x => x - 1; const sqr = x => x * x; let seq = comp(dec)(comp(sqr)(inc));  seq(2); // 8 

seq(2) transformed dec(sqr(inc(2))) , application order inc(2)...sqr...dec. functions invoked in reverse order in passed comp. isn't intuitive javascript programmers, since they're used method chaining, goes left right:

o = {   x: 2,   inc() { return this.x + 1, },   dec() { return this.x - 1, },   sqr() { return this.x * this.x, } }  o.dec().sqr().inc(); // 2 

i consider confusing. here's reversed composition:

const compl = f => g => x => g(f(x)); let seql = compl(dec)(compl(sqr)(inc));  seql(2); // 2 

are there reasons why function composition goes right left?

your question order of arguments in definition of function composition operator rather right- or left-associativity. in mathematics, write "f o g" (equivalent comp(f)(g) in definition) mean function takes x , returns f(g(x)). "f o (g o h)" , "(f o g) o h" equivalent , both mean function maps each argument x f(g(h(x))).

that said, write f;g (equivalent compl(f)(g) in code) mean function maps x g(f(x)). thus, both (f;g);h , f;(g;h) mean function mapping x h(g(f(x))).

a reference: https://en.wikipedia.org/wiki/function_composition#alternative_notations


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -