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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With