“call-cc” patterns in Scala?

Spread the love

Question Description

I found a good article, 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 ?

Practice As Follows

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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.