【发布时间】:2011-10-14 14:53:43
【问题描述】:
我正在尝试使用 Scala (2.9.0) 延续来构建一个看似阻塞的 API,但实际上是异步的。假设你想写这样的东西:
if(ask("Continue?")) //Prompts Yes/No
name = input("Enter your name")
如果用户按下是,ask 返回一个布尔值,input 要求一个值。想象一下这是从 Web 服务器调用的,其中 ask 和 input 不会阻塞任何线程,它们只是在显示带有提示的页面之前将延续存储在 Map (或会话,无关紧要)中(释放大部分资源)。当响应返回时,它会在 Map 中查找延续并恢复代码。
到目前为止的问题是,我似乎无法找到合适的方法来定义 ask 和 input 以使用延续而不将调用上下文的返回类型作为参数传递。
我得到的最接近的是做类似的事情:
#!/bin/sh
exec scala -P:continuations:enable -deprecation "$0" "$@"
!#
import util.continuations._
//Api code
def display[T](prompt: String) = shift {
cont: (Unit => T) => {
println(prompt)
cont()
}
}
//Client code
def foo() : Int = reset {
display[Int]("foo!") // <-- how do I get rid of the type annotation?
5
}
def bar() : Unit = reset {
display[Unit]("bar!")
}
println(foo())
bar()
我真的很想摆脱对display 的调用的类型注释。有谁知道实现这一目标的方法?我不在乎 API 定义是否变得丑陋,只要客户端代码变得更简单。
谢谢!
【问题讨论】:
-
发布您的答案作为答案。
标签: scala continuations