title: How to apply callcc so that it provides an escape continuation mechanism for use with the continuation monad
body: <p>I try to implement the continuation monad in Javascript to handle continuation passing style and asynchronous control flows. Here is my continuation monad for learning:</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>// auxiliary functions
  
  const log = prefix =&gt; x =&gt; console.log(prefix, x);
  const addk = x =&gt; y =&gt; k =&gt; setTimeout((x, y) =&gt; k(x + y), 0, x, y);
  const inck = x =&gt; k =&gt; setTimeout(x =&gt; k(x + 1), 0, x);
  const sqr = x =&gt; x * x;
  
  
  // continuation monad
  
  const cont = {
    of: x =&gt; k =&gt; k(x),
  
    map: ftor =&gt; f =&gt; k =&gt; ftor(x =&gt; k(f(x))),
  
    ap: ftor =&gt; gtor =&gt; k =&gt; ftor(x =&gt; gtor(f =&gt; k(f(x)))),
  
    chain: ftor =&gt; mf =&gt; k =&gt; ftor(x =&gt; mf(x) (k)),
  
    callcc: f =&gt; k =&gt; f(x =&gt; () =&gt; k(x)) (k)
  };
  
  
  // map a normal, unary function with an asynchronous function:
  
  cont.map(inck(9)) (sqr) (log("map"));
  
  
  // chain two asynchronous CPS computations with an asynchronous binary CPS function
  
  const comp1 = cont.map(inck(4)) (sqr);
  const comp2 = cont.map(inck(9)) (sqr);
  
  cont.chain(comp1) (x =&gt; cont.chain(comp2) (y =&gt; addk(x) (y))) (log("chain"));</code></pre>
  </div>
  </div>
  </p>
  
  <p>Apart from <code>cont.ap</code>, whose benefit doesn't reveal itself to me, everything works fine.</p>
  
  <p>Now I'd like to mimic the <code>throw</code>/<code>catch</code> mechanism of synchronous control flows in Javascript. <code>callcc</code> seems to fit, because it provides an escape continuation mechanism for use with continuation monads, as stated on <a href="http://hackage.haskell.org/package/transformers-0.5.2.0/docs/Control-Monad-Trans-Cont.html#v:callCC" rel="noreferrer">http://hackage.haskell.org/</a>.</p>
  
  <p>But I can't figure out how to apply <code>callcc</code> and I haven't found any suitable source that describes such an application.</p>