Scala 延续不编译
Scala continuations not compiling
我正在尝试 Scala 的延续库(使用 Scala 2.12.10)。我正在测试的代码——检查我是否理解这个概念——如下:
object Test {
import scala.util.continuations._
def run(): (Unit => Unit) = {
var x = 0;
reset {
while (x < 10) {
if (x == 5)
shift { cont: (Unit => Unit) =>
return cont
}
println(f"x = $x")
x += 1
}
}
}
def main(args: Array[String]): Unit = {
val cont = run()
cont()
}
}
我正在尝试的代码是为了打破 while 循环并允许调用者调用延续来恢复循环。但是,我收到一个错误:
Error:(9, 9) type mismatch; found : Unit required: Unit
@scala.util.continuations.cpsParam[Unit,Nothing]
if (x == 5)
我怀疑我必须在某个地方添加 @scala.util.continuations.cpsParam[Unit,Nothing]
,但是在随机的地方尝试之后,我不知道应该把它放在哪里。 如何更正我的代码以便编译?
我的build.sbt
:
name := "continuations"
version := "0.1"
scalaVersion := "2.12.10"
autoCompilerPlugins := true
libraryDependencies +=
"org.scala-lang.plugins" %% "scala-continuations-library" % "1.0.3"
addCompilerPlugin(
"org.scala-lang.plugins" % "scala-continuations-plugin_2.12.0" % "1.0.3")
scalacOptions += "-P:continuations:enable"
我能够通过将 else
分支添加到 reset
内的条件并将 run
的 return 类型设置为 Any
。我认为这个问题与 run
内部不同代码分支的类型 return 不一致有关,但我真的不知道是否有比 Any
更具体的类型可用于使事情正常工作。
object Test {
import scala.util.continuations._
def run():Any = {
var x = 0;
reset {
while (x < 10) {
if (x == 5)
shift { cont: (Unit => Unit) =>
return cont
} else shift { cont: (Unit => Unit) =>
cont()
}
println(f"x = $x")
x += 1
}
}
}
def main(args: Array[String]): Unit = {
val cont = run()
printf("Continuation called\n")
cont.asInstanceOf[Unit=>Unit]()
}
}
我正在尝试 Scala 的延续库(使用 Scala 2.12.10)。我正在测试的代码——检查我是否理解这个概念——如下:
object Test {
import scala.util.continuations._
def run(): (Unit => Unit) = {
var x = 0;
reset {
while (x < 10) {
if (x == 5)
shift { cont: (Unit => Unit) =>
return cont
}
println(f"x = $x")
x += 1
}
}
}
def main(args: Array[String]): Unit = {
val cont = run()
cont()
}
}
我正在尝试的代码是为了打破 while 循环并允许调用者调用延续来恢复循环。但是,我收到一个错误:
Error:(9, 9) type mismatch; found : Unit required: Unit
@scala.util.continuations.cpsParam[Unit,Nothing]
if (x == 5)
我怀疑我必须在某个地方添加 @scala.util.continuations.cpsParam[Unit,Nothing]
,但是在随机的地方尝试之后,我不知道应该把它放在哪里。 如何更正我的代码以便编译?
我的build.sbt
:
name := "continuations"
version := "0.1"
scalaVersion := "2.12.10"
autoCompilerPlugins := true
libraryDependencies +=
"org.scala-lang.plugins" %% "scala-continuations-library" % "1.0.3"
addCompilerPlugin(
"org.scala-lang.plugins" % "scala-continuations-plugin_2.12.0" % "1.0.3")
scalacOptions += "-P:continuations:enable"
我能够通过将 else
分支添加到 reset
内的条件并将 run
的 return 类型设置为 Any
。我认为这个问题与 run
内部不同代码分支的类型 return 不一致有关,但我真的不知道是否有比 Any
更具体的类型可用于使事情正常工作。
object Test {
import scala.util.continuations._
def run():Any = {
var x = 0;
reset {
while (x < 10) {
if (x == 5)
shift { cont: (Unit => Unit) =>
return cont
} else shift { cont: (Unit => Unit) =>
cont()
}
println(f"x = $x")
x += 1
}
}
}
def main(args: Array[String]): Unit = {
val cont = run()
printf("Continuation called\n")
cont.asInstanceOf[Unit=>Unit]()
}
}