How to discard a delimited continuation from within multiple nested functions?

两盒软妹~` 提交于 2019-12-10 17:33:47

问题


I study delimited continuations and am currently playing with discarding them to obtain an effect similar to raising exceptions.

Here is what causes me trouble:

const structure = type => cons => {
  const f = (f, args) =>
   ({["run" + type]: f, [Symbol.toStringTag]: type, [Symbol("args")]: args});

  return cons(f);
};

const Cont = structure("Cont")
  (Cont => f => Cont(f));

const runCont = tf => k =>
  tf.runCont(k);

const reset = tf =>
  of(tf.runCont(id));
  
const shift = f =>
  Cont(k => f(k).runCont(id));

const of = x =>
  Cont(k => k(x));
  
const liftM2 = f => tf => tg =>
  of(runCont(tf) (x => runCont(tg) (y => f(x) (y))));

const id = x => x;

const mulM = liftM2(x => y => x * y);
const addM = liftM2(x => y => x + y);
const subM = liftM2(x => y => x - y);

const z1 = mulM(of(5))
  (reset
    (addM
      (shift(k => of(3)))
        (of(3)))
  ).runCont(id); // 5 * 3 = 15 (as expected)

const z2 = mulM(of(5))
  (reset // A
    (mulM // B
      (addM
        (shift(k => of(3))) // C should unwind up to A instead of B
          (of(3)))
            (of(4)))
  ).runCont(id); // 5 * 3 * 4 = 60 (but 15 expected)

console.log(z1);
console.log(z2);

It seems as if I can unwind the stack only by a single frame. Is this by design of shift/reset or caused by a flaw in my implementation?

[EDIT]

I got it working in Haskell, i.e. it's an implementation issue:

reset :: ((a -> a) -> a) -> (a -> r) -> r
reset k f = f $ k id

shift :: ((a -> r) -> (r -> r) -> r) -> (a -> r) -> r
shift f k = f k id

return :: a -> (a -> r) -> r
return a k = k a

liftM2 :: (a -> b -> c) -> ((a -> r) -> r) -> ((b -> r) -> r) -> (c -> r) -> r
liftM2 f ma mb k = ma $ \a -> mb $ \b -> k (f a b)

example :: Num a => (a -> r) -> r
example = liftM2 (*) (return 5) (reset (liftM2 (*) (return 3) (liftM2 (+) (return 2) (shift (\k -> return 3)))))

回答1:


I think your liftM2 is broken, as it is not lazy. Instead of using of, it should construct a new continuation:

const liftM2 = f => tf => tg =>
  Cont(k => runCont(tf) (x => runCont(tg) (y => k(f(x)(y)))));


来源:https://stackoverflow.com/questions/54721972/how-to-discard-a-delimited-continuation-from-within-multiple-nested-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!