How to fix my Fibonacci stream in Scala

混江龙づ霸主 提交于 2019-11-28 12:11:31
oxbow_lakes

That is because you have used a def. Try using a val:

lazy val fib: Stream[Int] 
  = 1 #:: 2 #:: (fib zip fib.tail map { case (x, y) => x + y })

Basically a def is a method; in your example you are calling the method each time and each time the method call constructs a new stream. The distinction between def and val has been covered on SO before, so I won't go into detail here. If you are from a Java background, it should be pretty clear.

This is another nice thing about scala; in Java, methods may be recursive but types and values may not be. In scala both values and types can be recursive.

You can do it the other way:


lazy val fibs = {
  def f(a: Int, b: Int): Stream[Int] = a #:: f(b, a + b)
  f(0, 1)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!