【发布时间】:2016-05-08 19:17:12
【问题描述】:
我正在尝试使用 Scala 2.11.7 编译以下代码。
object LucasSeq {
val fibo: Stream[Int] = 0 #:: 1 #:: fibo.zip(fibo.tail).map { pair =>
pair._1 + pair._2
}
def firstKind(p: Int, q: Int): Stream[Int] = {
val lucas: Stream[Int] = 0 #:: 1 #:: lucas.zip(lucas.tail).map { pair =>
p * pair._2 - q * pair._1
}
lucas
}
}
fibo 基于Fibonacci sequence example in Scala's Stream documentation,并且可以正常工作。
但是,firstKind 函数尝试使用参数p 和q 泛化序列(生成Lucas sequences of the first kind),出现以下错误:
LucasSeq.scala:7: error: forward reference extends over definition of value lucas
val lucas: Stream[Int] = 0 #:: 1 #:: lucas.zip(lucas.tail).map { pair =>
^
one error found
基本上都是一样的代码,那为什么在函数外却在函数内不行呢?
这个错误信息让我之前的许多程序员感到困惑。我考虑过……
- So just don't put that code in a function — 但我确实想要一个函数。
-
implicit val lucas— 没有帮助。 - Self-references can only be used in lazy expressions — 但这 很懒,对吧?
-
Compile with
-Xprint:typerdiagnostics — 不知道如何处理这些信息。 - Is it a shadowing issue? — 不,我使用的标识符不会冲突。
- Compiler bug? — 我希望不会。引用的错误应该已在 2.11.7 中修复。
我可能会继续阅读几个小时,但我认为此时最好寻求帮助。我正在寻找解决方案和解释。 (我熟悉函数式编程,但对 Scala 很陌生,所以如果解释涉及“综合”和“隐式”等术语,那么我可能还需要对此进行额外解释。)
【问题讨论】:
-
“使用 -Xprint:typer 诊断进行编译——不确定如何处理这些信息。”请在此处粘贴。
-
@Jus12 粘贴输出有什么意义吗?任何拥有 Scala 编译器的人都可以通过编译上面的代码来重现它。
标签: scala compiler-errors lazy-sequences forward-reference