【问题标题】:Scala continuations not compilingScala 延续不编译
【发布时间】:2020-04-06 00:53:07
【问题描述】:

我正在尝试 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 循环并允许调用者调用延续来恢复循环。但是,我收到一个错误:

错误:(9, 9) 类型不匹配;找到:所需单位:单位
@scala.util.continuations.cpsParam[Unit,Nothing]
如果 (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"

【问题讨论】:

    标签: scala continuations


    【解决方案1】:

    我能够通过将else 分支添加到reset 内的条件并将run 的返回类型设置为Any 来使代码工作。我认为问题与从 run 内部不同代码分支返回的类型不同意有关,但我真的不知道是否有比 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]()
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 2013-07-01
      • 2017-07-15
      • 2011-06-01
      • 2011-08-28
      相关资源
      最近更新 更多