【问题标题】:Using Scala continuations for non-blocking APIs为非阻塞 API 使用 Scala 延续
【发布时间】: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 服务器调用的,其中 askinput 不会阻塞任何线程,它们只是在显示带有提示的页面之前将延续存储在 Map (或会话,无关紧要)中(释放大部分资源)。当响应返回时,它会在 Map 中查找延续并恢复代码。

到目前为止的问题是,我似乎无法找到合适的方法来定义 askinput 以使用延续而不将调用上下文的返回类型作为参数传递。

我得到的最接近的是做类似的事情:

#!/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


【解决方案1】:

我终于明白了:

#!/bin/sh
exec scala -P:continuations:enable -deprecation "$0" "$@"
!#
import util.continuations._

class Display(val resume: (Unit => Any)) extends Throwable

//Api code
def display(prompt: String) = shift {
  cont: (Unit => Any) => {
        println(prompt)
        throw new Display(cont)
    }
}

//Client code
def foo() : Int = reset {
  display("foo!")
  5
}

def bar() : Unit = reset {
  display("bar!")
}

//Framework
try {
    foo()
} catch {
    case d: Display => println(d.resume())
}

try {
    bar()
} catch {
    case d: Display => d.resume() 
}

诀窍是接受返回 Any(Homeresque:D'oh!)并返回 Nothing 的方法。

如果你想实现一些返回值的东西,比如ask,你可以这样做:

class Ask(val resume: (Boolean => Any)) extends Throwable

//Api code
def ask(prompt: String) = shift {
  cont: (Boolean => Any) => {
        println(prompt)
        throw new Ask(cont)
    }
}

在上面的代码中,ask 返回一个Boolean

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-22
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    相关资源
    最近更新 更多