I am trying to write in Scala a function similar to the Haskell "iterate" function. Given a value x and a function f, iterate should return a Stream composed of the values x, f(x), f(f(x)), etc...
Here is the code I wrote:
object current {
def iterate[A](f: A => A, x: A): Stream[A] = {
val res: Stream[A] = x #:: res.map(f)
return res
}
def double(x: Int) = x * 2
def main(args: Array[String]): Unit = {
val str: Stream[Int] = iterate(double, 2)
}
}
When I try to compile it, I get the error:
forward reference extend over the definition of value res (at line 3)
How can I correct my code to generate the proper Stream ?