gpt4 book ai didi

javascript - 具有 rest operator、reducer 和 mapper 的函数组合

转载 作者:行者123 更新时间:2023-11-30 11:37:06 25 4
gpt4 key购买 nike

我正在关注一篇关于 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)

最佳答案

最后我找到了一种实现似乎工作正常的组合的方法

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

关于javascript - 具有 rest operator、reducer 和 mapper 的函数组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44022945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com