函数组合是从右往左组合的:
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 . (g . h) === (f . g) . h
?无论如何,如果一直都是这样的,并且许多人已经习惯了,我不想质疑它。 - user6445533compl
函数是“左结合”的时候,实际上你交换了参数,这让我完全困惑了。 - Bergi