最终 R.sum 的 ramda 传感器
ramda transducers with final R.sum
我正在尝试了解 Ramda 的转换器。这是文档中的一个稍微修改过的示例:
const numbers = [1, 2, 3, 4];
const isOdd = (x) => x % 2 === 1;
const firstFiveOddTransducer = R.compose(R.filter(isOdd), R.take(5));
R.transduce(firstFiveOddTransducer, R.flip(R.append), [], R.range(0, 100)); //=> [ 1, 3, 5, 7, 9 ]
但是如果我想对结果数组的元素求和怎么办?以下(只需将 R.sum
添加到 R.compose
中)不起作用:
const firstFiveOddTransducer = R.compose(R.filter(isOdd), R.take(5), R.sum);
我会做这样的事情,
只是在初始 0 值之上累积
const list = [1, 2, 3, 4, 5];
const isOdd = R.filter(n => n % 2);
const transducer = R.compose(isOdd);
const result = R.transduce(transducer, R.add, 0, list);
console.log(
'result',
result,
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>
我正在尝试了解 Ramda 的转换器。这是文档中的一个稍微修改过的示例:
const numbers = [1, 2, 3, 4];
const isOdd = (x) => x % 2 === 1;
const firstFiveOddTransducer = R.compose(R.filter(isOdd), R.take(5));
R.transduce(firstFiveOddTransducer, R.flip(R.append), [], R.range(0, 100)); //=> [ 1, 3, 5, 7, 9 ]
但是如果我想对结果数组的元素求和怎么办?以下(只需将 R.sum
添加到 R.compose
中)不起作用:
const firstFiveOddTransducer = R.compose(R.filter(isOdd), R.take(5), R.sum);
我会做这样的事情, 只是在初始 0 值之上累积
const list = [1, 2, 3, 4, 5];
const isOdd = R.filter(n => n % 2);
const transducer = R.compose(isOdd);
const result = R.transduce(transducer, R.add, 0, list);
console.log(
'result',
result,
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>