用于Scala延续

时间:2010-10-26 09:44:18

标签: scala continuations

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

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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()
    }
  }
}