3

我被我的短路和堆栈安全传感器实现所困扰:

const loop = f => {
   let acc = f();

   while (acc && acc.type === tailRec)
     acc = f(...acc.args);

   return acc;
};

const tailRec = (...args) =>
   ({type: tailRec, args});

const arrFoldk = f => acc_ => xs =>
  loop((acc = acc_, i = 0) =>
    i === xs.length
      ? acc
      : f(acc) (xs[i]) (acc_ => tailRec(acc_, i + 1)));

const liftk2 = f => x => y => k =>
  k(f(x) (y));

const isOdd = n => n & 1 === 1;
const concat = xs => ys => xs.concat(ys);
const comp = f => g => x => f(g(x));
const id = x => x;

const filterReduce = filter => reduce => acc => x => k =>
  filter(x)
    ? reduce(acc) (x) (k)
    : k(acc);

const takeReduce = n => reduce => acc => x => k =>
  acc.length === n
    ? reduce(acc) (x) (id)
    : reduce(acc) (x) (k);

const fx = filterReduce(isOdd),
  fy = takeReduce(3),
  fz = comp(fy) (fx);

const transducek = (...fs) => xs =>
  arrFoldk(fs.reduce((f, g) => comp(f) (g), id) (liftk2(concat))) ([]);

const r1 = arrFoldk(fz(liftk2(concat))) ([]) ([1,2,3,4,5,6,7,8,9]);
const r2 = transducek(fx, fy) ([1,2,3,4,5,6,7,8,9]);

console.log(r1); // [1,3,5]
console.log(r2); // xs => ...

我正在查看代码,它非常清楚地告诉我,产生r1和的计算r2基本上是相同的。为什么我在应用transduce辅助功能时没有得到相同的结果?

4

1 回答 1

2

不确定这些是否是您正在寻找的错误,但这两件事让我印象深刻:

  1. 您已包含xs在 的签名中transduceK,但从不使用此参数调用组合函数。要么添加(xs)到最后,要么只是做:

    const transducek = (...fs) =>
      arrFoldk(fs.reduce((f, g) => comp(f) (g), id) (liftk2(concat))) ([]);
    
  2. 等价于comp (fy) (fx)is[fx, fy].reduceRight((g, h) => comp (g) (h), id) [fx, fy].reduce((f, g) => comp(g) (f), id)

通过这些更改,我认为一切都按预期进行:

const loop = f => {
   let acc = f();

   while (acc && acc.type === tailRec)
     acc = f(...acc.args);

   return acc;
};

const tailRec = (...args) =>
   ({type: tailRec, args});

const arrFoldk = f => acc_ => xs =>
  loop((acc = acc_, i = 0) =>
    i === xs.length
      ? acc
      : f(acc) (xs[i]) (acc_ => tailRec(acc_, i + 1)));

const liftk2 = f => x => y => k =>
  k(f(x) (y));

const isOdd = n => n & 1 === 1;
const concat = xs => ys => xs.concat(ys);
const comp = f => g => x => f(g(x));
const id = x => x;

const filterReduce = filter => reduce => acc => x => k =>
  filter(x)
    ? reduce(acc) (x) (k)
    : k(acc);

const takeReduce = n => reduce => acc => x => k =>
  acc.length === n
    ? reduce(acc) (x) (id)
    : reduce(acc) (x) (k);

const fx = filterReduce(isOdd),
  fy = takeReduce(3),
  fz = comp(fy) (fx);

const transducek = (...fs) =>
  arrFoldk(fs.reduce((f, g) => comp(g) (f), id) (liftk2(concat))) ([]);

const r1 = arrFoldk(fz(liftk2(concat))) ([]) ([1,2,3,4,5,6,7,8,9]);
const r2 = transducek(fx, fy) ([1,2,3,4,5,6,7,8,9]);

console.log(r1); // [1,3,5]
console.log(r2); // [1,3,5]

于 2018-12-11T21:08:20.987 回答