开发者

"call-cc" patterns in Scala?

I found a good art开发者_StackOverflow社区icle, about call with current continuation patterns. As I understand, they use Scheme and undelimited continuations. Can the patterns from the article be implemented in Scala? Is there any article about delimited continuations patterns in Scala ?


Yes, they absolutely can. callCC looks like this in Scala:

def callCC[R, A, B](f: (A => Cont[R, B]) => Cont[R, A]): Cont[R, A] =
  Cont(k => f(a => Cont(_ => k(a))) run k)

Where Cont is a data structure that captures a continuation:

case class Cont[R, A](run: (A => R) => R) {
  def flatMap[B](f: A => Cont[R, B]): Cont[R, B] =
    Cont(k => run(a => f(a) run k))
  def map[B](f: A => B): Cont[R, B] =
    Cont(k => run(a => k(f(a))))
}

Here's how you might use it to simulate checked exceptions:

def divExcpt[R](x: Int, y: Int, h: String => Cont[R, Int]): Cont[R, Int] =
  callCC[R, Int, String](ok => for {
    err <- callCC[R, String, Unit](notOK => for {
             _ <- if (y == 0) notOK("Denominator 0") else Cont[R, Unit](_(()))
             r <- ok(x / y)
           } yield r)
    r <- h(err)
  } yield r)

You would call this function as follows:

scala> divExcpt(10, 2, error) run println   
5

scala> divExcpt(10, 0, error) run println
java.lang.RuntimeException: Denominator 0


Scala has an implementation of typed delimited continuations which used to be shipped with the compiler and standard library, but has been extracted to an external module and pretty much left to rot since then. It's a great shame, and I encourage anyone who's interested in delimited continuations to show that they care about its existence by using and contributing to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜