我关注Transducers in JavaScript的文章,特别是我定义了以下功能
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);
现在我想定义一个合成运算符
const more = (f, g) => (...args) => f(g(...args));
我发现它在以下情况下工作
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);
整个脚本是online。
我不明白为什么我也不能将最后一个函数(sumOf
)与组合运算符(more
)连接起来。理想情况下,我想写
res2 = reduceWith(more(squares,divtwo,sumOf), 0, one2ten);
res3 = reduceWith(more(divtwo,squares,sumOf), 0, one2ten);
但它没有用。
修改
很明显,我最初的尝试是错误的,但即使我将构图定义为
const compose = (...fns) => x => fns.reduceRight((v, fn) => fn(v), x);
我仍然无法用compose(divtwo,squares)(sumOf)
compose(divtwo,squares,sumOf)
答案 0 :(得分:3)
最后,我找到了一种方法来实现似乎工作正常的组合
const more = (f, ...g) => {
if (g.length === 0) return f;
if (g.length === 1) return f(g[0]);
return f(more(...g));
}
这是另一种带有reducer并且没有递归的解决方案
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);
完整脚本online
答案 1 :(得分:0)
您的more
仅使用2个功能运行。问题在于more(squares,divtwo)(sumOf)
你执行一个函数,这里more(squares,divtwo, sumOf)
你返回一个期望另一个调用的函数(例如const f = more(squares,divtwo, sumOf); f(args)
)。
为了拥有可变数量的可组合函数,您可以为函数组合定义不同的more
。组成任意数量函数的常规方法是compose
或pipe
函数(区别在于参数顺序:pipe
在执行顺序中从左到右执行函数,compose
- 相反的。)
定义pipe
或compose
的常规方式:
const pipe = (...fns) => x => fns.reduce((v, fn) => fn(v), x);
const compose = (...fns) => x => fns.reduceRight((v, fn) => fn(v), x);
您可以将x
更改为(...args)
以符合您的more
定义。
现在您可以逐个执行任意数量的功能:
const pipe = (...fns) => x => fns.reduce((v, fn) => fn(v), x);
const compose = (...fns) => x => fns.reduceRight((v, fn) => fn(v), x);
const inc = x => x + 1;
const triple = x => x * 3;
const log = x => { console.log(x); return x; } // log x, then return x for further processing
// left to right application
const pipe_ex = pipe(inc, log, triple, log)(10);
// right to left application
const compose_ex = compose(log, inc, log, triple)(10);
答案 2 :(得分:0)
我仍然无法用
替换compose(divtwo,squares)(sumOf)
compose(divtwo,squares,sumOf)
是的,它们并不等同。你不应该尝试!请注意,divtwo
和squares
是传感器,而sumOf
是 reducer 。他们有不同的类型。不要构建混合它们的more
函数。
如果您坚持使用动态数量的传感器,请将它们放入阵列中:
[divtwo, squares].reduceRight((t, r) => t(r), sumOf)