【问题标题】:Scala continuation type errorScala延续类型错误
【发布时间】:2013-07-01 06:54:32
【问题描述】:

我正在阅读来自 here 的 scala 延续博客文章。不幸的是,这在 scala 2.10.0 上不起作用:

def f():Int @cps[Int,Int] = {shift { (k:Int=>Int) => k(6) } - 1} 
<console>:10: error: wrong number of type arguments for util.continuations.cps, should be 1
       def f():Int @cps[Int,Int] = {shift { (k:Int=>Int) => k(6) } - 1} 
                ^
<console>:10: error: type mismatch;
 found   : Int @scala.util.continuations.cpsSynth 

@scala.util.continuations.cpsParam[Int,Int]
 required: Int
       def f():Int @cps[Int,Int] = {shift { (k:Int=>Int) => k(6) } - 1} 

如果我尝试了建议的类型,同样的交易:

def f():Int @cpsParam[Int,Int] = {shift { (k:Int=>Int) => k(6) } - 1} 
<console>:4: error: type mismatch;
 found   : Int @scala.util.continuations.cpsSynth
@scala.util.continuations.cpsParam[Int,Int]
 required: Int
object $eval {

如果我添加一个未使用的输入参数,它不会抱怨:

def f2(x:Int):Int @cpsParam[Int, Int=>Int] = shift { (k:Int=>Int) => k } -1
f2: (x: Int)Int @scala.util.continuations.cpsParam[Int,Int => Int]

reset(f2(1))(0)
res12: Int = -1

你能解释一下为什么会这样吗?

【问题讨论】:

    标签: scala continuations


    【解决方案1】:

    您已经发现需要将 cps 更改为 cpsParam

    如果您在object 内编译REPL 之外的行,它实际上可以正常工作。您所看到的是 REPL 在幕后所做的工作以打印出对其读取内容的评估。在 REPL 中,当您键入并看到类似以下内容时:

    scala> def f() = 1
    f: ()Int
    

    由于某种我无法解释的原因,生成f: ()Int 字符串的代码将f 的结果分配给如下虚拟变量:lazy val $result = f。如果您使用 -Xprint:parser 选项启动 REPL,您可以看到它的实际效果。它将揭露很多幕后发生的事情。

    很遗憾,创建虚拟赋值的代码不理解延续插件,合成的代码无效。

    要解决这个问题,您可以在单个语句中在对象内定义 f,这将绕过惰性 val 语句:

    $ scala -P:continuations:enable               
    Welcome to Scala version 2.10.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_09).
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> import util.continuations._
    import util.continuations._
    
    scala> object F { def f():Int @cpsParam[Int,Int] = {shift { (k:Int=>Int) => k(6) } - 1} }
    defined module F
    
    scala> reset{ F.f() }
    res0: Int = 5
    

    当您向 f 添加虚拟参数时,REPL 不会尝试将结果分配给 val,这就是您的第二个示例有效的原因。

    【讨论】:

    • 这很有趣。感谢您的回复。
    猜你喜欢
    • 1970-01-01
    • 2011-08-29
    • 2017-07-06
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    相关资源
    最近更新 更多