功能组合与休息操作员,减速器和映射器 [英] function composition with rest operator, reducer and mapper
问题描述
我正在关于 JavaScript中的传感器以及特别是我定义了以下函数
I'm following an article about Transducers in JavaScript, and in particular I have defined the following functions
const reducer = (acc, val) => acc.concat([val]);
const reduceWith = (reducer, seed, iterable) => {
let accumulation = seed;
for (const value of iterable) {
accumulation = reducer(accumulation, value);
}
return accumulation;
}
const map =
fn =>
reducer =>
(acc, val) => reducer(acc, fn(val));
const sumOf = (acc, val) => acc + val;
const power =
(base, exponent) => Math.pow(base, exponent);
const squares = map(x => power(x, 2));
const one2ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
res1 = reduceWith(squares(sumOf), 0, one2ten);
const divtwo = map(x => x / 2);
现在我想定义一个合成运算符
Now I want to define a composition operator
const more = (f, g) => (...args) => f(g(...args));
,我看到它在以下情况下工作
and I see that it is working in the following cases
res2 = reduceWith(more(squares,divtwo)(sumOf), 0, one2ten);
res3 = reduceWith(more(divtwo,squares)(sumOf), 0, one2ten);
相当于
res2 = reduceWith(squares(divtwo(sumOf)), 0, one2ten);
res3 = reduceWith(divtwo(squares(sumOf)), 0, one2ten);
整个脚本是在线。
我不明白为什么我不能连接最后一个函数( sumOf
)与组合运算符(更多
)。理想情况下,我想写
I don't understand why I can't concatenate also the last function (sumOf
) with the composition operator (more
). Ideally I'd like to write
res2 = reduceWith(more(squares,divtwo,sumOf), 0, one2ten);
res3 = reduceWith(more(divtwo,squares,sumOf), 0, one2ten);
但不行。
修改
很明显,我的初始尝试是错误的,但即使我将组合定义为
It is clear that my initial attempt was wrong, but even if I define the composition as
const compose = (...fns) => x => fns.reduceRight((v, fn) => fn(v), x);
我仍然无法替换 compose(divtwo,squares)(sumOf)
与 compose(divtwo,squares,sumOf)
推荐答案
最后,我找到了一种方法来实现似乎工作正常的组合
Finally I've found a way to implement the composition that seems to work fine
const more = (f, ...g) => {
if (g.length === 0) return f;
if (g.length === 1) return f(g[0]);
return f(more(...g));
}
更好的解决方案
这里是另一个解决方案,使用reducer并且没有递归
Better solution
Here it is another solution with a reducer and no recursion
const compose = (...fns) => (...x) => fns.reduceRight((v, fn) => fn(v), ...x);
const more = (...args) => compose(...args)();
使用:
res2 = reduceWith(more(squares,divtwo,sumOf), 0, one2ten);
res3 = reduceWith(more(divtwo,squares,sumOf), 0, one2ten);
完整脚本在线
这篇关于功能组合与休息操作员,减速器和映射器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!