javascript-如何为应用程序实现协程?

前端之家收集整理的这篇文章主要介绍了javascript-如何为应用程序实现协程? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这是一个协程,可以避免像(chain(m)(chain(…)))这样的嵌套模式进行单子计算:

const some = x => none => some => some(x);
const none = none => some => none;

const option = none => some => tx => tx(none) (some);
const id = x => x;

const of = some;
const chain = fm => m => none => some => m(none) (x => fm(x) (none) (some));

const doM = (chain,of) => gf => {
  const it = gf();

  const loop = ({done,value}) =>
    done
      ? of(value)
      : chain(x => loop(it.next(x))) (value);

  return loop(it.next());
};

const tx = some(4),ty = some(5),tz = none;

const data = doM(chain,of) (function*() {
  const x = yield tx,y = yield ty,z = yield tz;

  return x + y + z;
});

console.log(
  option(0) (id) (data)); // 0

但是我无法为应用计算实现等效的协程:

const some = x => none => some => some(x);
const none = none => some => none;

const option = none => some => tx => tx(none) (some);
const id = x => x;

const of = some;
const map = f => t => none => some => t(none) (x => some(f(x)));
const ap = tf => t => none => some => tf(none) (f => t(none) (x => some(f(x))));

const doA = (ap,value},initial) =>
    done
      ? value
      : ap(of(x => loop(it.next(x)))) (value);

  return loop(it.next());
};

const tx = some(4),tz = none;

const data = doA(ap,z = yield tz;

  return x + y + z;
});

console.log(
  option(0) (id) (data)); // none => some => ...

这应该可以,但是不能.附加的函子包装来自何处?我想我在这里的递归有点迷路了.

顺便说一下,我知道这仅适用于确定性函子/单子.

最佳答案

I’m not able to implement an equivalent coroutine for applicative computations

是的,因为生成函数是一元函数,而不仅仅是适用函数. yield表达式的操作数可以取决于先前的yield表达式的结果-这是monad的特征.

Where does the additional functorial wrapping come from? I guess I am a bit lost here.

您正在做ap(of(…))(…)-根据Applicative laws,这等效于map(…)(…).与第一个代码段中的链调用相比,这不会对结果进行任何解包,因此您会得到一个嵌套的也许类型(在您的实现中,它被编码为一个函数).

原文链接:https://www.f2er.com/js/531129.html

猜你在找的JavaScript相关文章