title: How to implement a coroutine for applicative computations?
body: <p>Here is a coroutine that avoids nested patterns like (<code>chain(m) (chain(...))</code> for monadic computations:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const some = x =&gt; none =&gt; some =&gt; some(x);
  const none = none =&gt; some =&gt; none;
  
  const option = none =&gt; some =&gt; tx =&gt; tx(none) (some);
  const id = x =&gt; x;
  
  const of = some;
  const chain = fm =&gt; m =&gt; none =&gt; some =&gt; m(none) (x =&gt; fm(x) (none) (some));
  
  const doM = (chain, of) =&gt; gf =&gt; {
    const it = gf();
  
    const loop = ({done, value}) =&gt;
      done
        ? of(value)
        : chain(x =&gt; 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</code></pre>
  </div>
  </div>
  </p>
  
  <p>But I'm not able to implement an equivalent coroutine for applicative computations:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const some = x =&gt; none =&gt; some =&gt; some(x);
  const none = none =&gt; some =&gt; none;
  
  const option = none =&gt; some =&gt; tx =&gt; tx(none) (some);
  const id = x =&gt; x;
  
  const of = some;
  const map = f =&gt; t =&gt; none =&gt; some =&gt; t(none) (x =&gt; some(f(x)));
  const ap = tf =&gt; t =&gt; none =&gt; some =&gt; tf(none) (f =&gt; t(none) (x =&gt; some(f(x))));
  
  const doA = (ap, of) =&gt; gf =&gt; {
    const it = gf();
  
    const loop = ({done, value}, initial) =&gt;
      done
        ? value
        : ap(of(x =&gt; loop(it.next(x)))) (value);
  
    return loop(it.next());
  };
  
  const tx = some(4),
    ty = some(5),
    tz = none;
  
  const data = doA(ap, of) (function*() {
    const x = yield tx,
      y = yield ty,
      z = yield tz;
  
    return x + y + z;
  });
  
  console.log(
    option(0) (id) (data)); // none =&gt; some =&gt; ...</code></pre>
  </div>
  </div>
  </p>
  
  <p>This should work, but it doesn't. Where does the additional functorial wrapping come from? I guess I am a bit lost in recursion here.</p>
  
  <p>By the way I know that this only works for deterministic functors/monads.</p>