1

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);

スクリプト全体がオンラインです。

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)

4

3 に答える 3