Question

How are people using continuations on a larger and smaller scale in Scala?

Are any parts of the Scala standard library written in CPS?

Are there any major performance penalties in using continuations?

Was it helpful?

Solution

I'm using this to turn asynchronous functions of the form def func(...)(followup: Result => Unit): Unit so that instead of writing

foo(args){result1 => 
  bar(result1){result2 => 
     car(result2) {result3 =>
       //etc.
     }
  }
}

you can write

val result1 = foo(args)
val result2 = bar(result1)
val result3 = car(result2)

or

car(bar(foo(args)))

(note: the functions are not limited to one argument or just the use of previous results as arguments)

See http://www.tikalk.com/java/blog/asynchronous-functions-actors-and-cps

OTHER TIPS

Scala-ARM (Automatic-Resource-Management) uses delimited continuations

import java.io._
import util.continuations._
import resource._
def each_line_from(r : BufferedReader) : String @suspendable =
  shift { k =>
    var line = r.readLine
    while(line != null) {
      k(line)
      line = r.readLine
    }
  }
reset {
  val server = managed(new ServerSocket(8007)) !
  while(true) {
    // This reset is not needed, however the  below denotes a "flow" of execution that can be deferred.
    // One can envision an asynchronous execuction model that would support the exact same semantics as below.
    reset {
      val connection = managed(server.accept) !
      val output = managed(connection.getOutputStream) !
      val input = managed(connection.getInputStream) !
      val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(output)))
      val reader = new BufferedReader(new InputStreamReader(input))
      writer.println(each_line_from(reader))
      writer.flush()
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top