为什么Javascript中的函数组合是从右到左组合的?

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

函数组合从右到左组合:

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)转化为dec(sqr(inc(2))),申请顺序为inc(2)...sqr...dec。因此,函数的调用顺序与传递给 comp 的顺序相反。这对 Javascript 程序员来说并不直观,因为他们习惯于从左到右的方法链接:

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

o.dec().sqr().inc(); // 2

我认为这令人困惑。这是一个颠倒的构图:

const flipped = f => g => x => g(f(x));
let seql = flipped(dec)(flipped(sqr)(inc));

seql(2); // 2

函数组合从右到左有什么原因吗?

您的问题实际上是关于函数组合运算符定义中参数的顺序,而不是右结合性或左结合性。在数学中,我们通常写"f o g"(相当于你定义中的comp(f)(g))来表示取x和returns f(g(x))的函数。因此 "f o (g o h)" 和 "(f o g) o h" 是等价的,都表示将每个参数 x 映射到 f(g(h(x))).

的函数

也就是说,我们有时会写成 f;g(相当于代码中的 compl(f)(g))来表示将 x 映射到 g(f(x)) 的函数。因此,(f;g);h 和 f;(g;h) 都表示将 x 映射到 h(g(f(x))) 的函数。

参考:https://en.wikipedia.org/wiki/Function_composition#Alternative_notations

回答原题:为什么函数组合是从右到左组合的?

  1. 所以它传统上是用数学制作的
  2. comp(f)(g)(x)f(g(x))
  3. 的顺序相同
  4. 创建反向或正向构图很简单(参见示例)

正向函数组成:

const comp = f => g => x => f(g(x));
const flip = f => x => y => f(y)(x);
const flipped = flip(comp);

const inc = a => a + 1;
const sqr = b => b * b;

   comp(sqr)(inc)(2); // 9, since 2 is first put into inc then sqr
flipped(sqr)(inc)(2); // 5, since 2 is first put into sqr then inc

这种调用函数的方式被称为 currying,其工作方式如下:

// the original:
comp(sqr)(inc)(2); // 9

// is interpreted by JS as:
( ( ( comp(sqr) ) (inc) ) (2) ); // 9 still (yes, this actually executes!)

// it is even clearer when we separate it into discrete steps:
const compSqr = comp(sqr); // g => x => sqr(g(x))
compSqr(inc)(2);   // 9 still
const compSqrInc = compSqr(inc); // x => sqr(x + 1)
compSqrInc(2);     // 9 still
const compSqrInc2 = compSqrInc(2); // sqr(3)
compSqrInc2;       // 9 still

所以函数是从左到右组合和解释(由 JS 解释器)的,而在执行时,它们的值从右到左流过每个函数。简而言之:先由外而内,再由内而外。

但是flip有一个限制,翻转组合不能与自身组合形成“高阶组合”:

const comp2 = comp(comp)(comp);
const flipped2 = flipped(flipped)(flipped);
const add = x => y => x + y;

   comp2(sqr)(add)(2)(3); // 25
flipped2(sqr)(add)(2)(3); // "x => f(g(x))3" which is nonsense

结论:从右到左的顺序是traditional/conventional但不直观。