【问题标题】:How to discard a delimited continuation from within multiple nested functions?如何从多个嵌套函数中丢弃定界延续?
【发布时间】:2019-07-10 08:14:25
【问题描述】:

我研究了定界延续,目前正在尝试丢弃它们以获得类似于引发异常的效果。

这就是给我带来麻烦的原因:

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);

似乎我只能将堆栈展开一帧。这是由shift/reset 设计的还是由我的实现中的缺陷引起的?

[编辑]

我让它在 Haskell 中工作,即这是一个实现问题:

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)))))

【问题讨论】:

    标签: javascript haskell functional-programming continuations delimited-continuations


    【解决方案1】:

    我认为你的liftM2 坏了,因为它并不懒惰。与其使用of,不如构造一个新的延续:

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

    【讨论】:

    • 我花了几个小时寻找这个。 of 不是 Cont,现在很明显。谢谢!
    • 酷,这只是一种预感,但我没有费心通过测试来确认它...... :-)
    猜你喜欢
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 2012-04-24
    • 2013-10-22
    • 1970-01-01
    • 2019-03-19
    相关资源
    最近更新 更多