17

人们如何在 Scala 中使用更大和更小规模的延续?

Scala 标准库的任何部分都是用 CPS 编写的吗?

使用延续是否有任何重大的性能损失?

4

2 回答 2

14

我用它来打开表单的异步函数def func(...)(followup: Result => Unit): Unit,而不是写

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

你可以写

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

或者

car(bar(foo(args)))

(注意:函数不限于一个参数或仅使用以前的结果作为参数)

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

于 2010-10-26T10:17:15.433 回答
7

Scala-ARM(自动资源管理)使用定界延续

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()
    }
  }
}
于 2010-10-26T10:32:38.260 回答