views:

206

answers:

2

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?

+10  A: 

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

IttayD
This is a pretty good example, it would probably have more didactic value if the nesting were deeper though :)
Alex Cruise
+7  A: 

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()
    }
  }
}
oluies
Excuse me, but what are the benefits of writing it like this? <br/><br/>So the continuation is `k`, which represents a println followed by a flush statement? I'm not seeing the benefits of using CPS in this case.
bruce.banner