Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"call-cc" patterns in Scala?

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 ?

like image 695
Michael Avatar asked May 14 '11 15:05

Michael


2 Answers

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
like image 105
Apocalisp Avatar answered Nov 11 '22 22:11

Apocalisp


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.

like image 40
Miles Sabin Avatar answered Nov 11 '22 21:11

Miles Sabin