我试图通过一个练习来理解 Javascript 中的组合和“排序”概念:定义。“作品”compose(f,g)(x) = f(g(x))定义。sequence(f,g)(x) = g(f(x))更多参数的“排序”sequence(f,g)(...args) = g(f(...args))const sequence2 = (f1, f2) => (...args) => f2( f1(...args) );const sequence = (f1, ...fRest) => fRest.reduce(sequence2, f1);const f1 = (a, b) => { console.log(`[f1] working on: ${a} and ${b}`); return a + b;}const f2 = a => `Result is ${a}`;const sequenceResult = sequence(f1, f1, f2)(1, 2, 5);console.log(sequenceResult);控制台显示:[f1] working on: 1 and 2[f1] working on: 3 and undefinedResult is NaN似乎序列中的第二个函数无法访问 args:我遗漏了一些东西,或者它是处理参数的错误方法?(序列函数适用于没有参数的函数)。
2 回答

MM们
TA贡献1886条经验 获得超2个赞
似乎序列中的第二个函数无法访问 args
是的,这是正常的和预期的。根据你给出的定义,
sequence(f1, f1, f2)(1, 2, 5);
相当于
f2(f1(f1(1, 2, 5)));
当然f2
,外部和外部f1
都不能访问传递给内部的参数f1
。

慕容708150
TA贡献1831条经验 获得超4个赞
函数只返回一个值。有两种方法可以通过多个返回值来扩充函数:
返回一个像元组一样的数组
而不是返回调用延续
这是后者的一个有趣的实现,它明确不适用于任何生产代码:
const pipek = g => f => x => y => k =>
k(g(x) (y) (f));
const addk = x => y => k =>
(console.log("apply addk to", x, y), k(x + y));
const main = pipek(addk)
(addk)
(2)
(3)
(k => k(4)); // we have to pass the 4th argument within the continuation
console.log(main(x => x)); // escape from the continuation
请注意,所有函数都是柯里化的,并且我使用了术语pipe
,这是 JS 中反向函数组合的常用术语。
添加回答
举报
0/150
提交
取消