I'm trying to compile the following code, using 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
is based on the Fibonacci sequence example in Scala's Stream
documentation, and it works.
However, the firstKind
function, which tries to generalize the sequence with parameters p
and q
(making Lucas sequences of the first kind), has the following error:
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
It's basically the same code, so why does it work outside the function but not inside a function?
This error message has puzzled many programmers before me. I've considered…
- So just don't put that code in a function — but I do want a function.
implicit val lucas
— doesn't help.- Self-references can only be used in lazy expressions — but this is lazy, right?
- Compile with
-Xprint:typer
diagnostics — not sure what to do with that information. - Is it a shadowing issue? — No, I'm using identifiers that don't clash.
- Compiler bug? — I hope not. The referenced bug should be already fixed in 2.11.7.
I could probably go on reading for hours, but I think it would be best to ask for help at this point. I'm looking for both a solution and an explanation. (I'm familiar with functional programming, but new to Scala, so if the explanation involves terms like "synthetic" and "implicit", then I'll probably need an additional explanation of that as well.)