How to fix my Fibonacci stream in Scala

前端 未结 2 726
小蘑菇
小蘑菇 2020-12-11 04:15

I defined a function to return Fibonacci stream as follows:

def fib:Stream[Int] = {
  Stream.cons(1,
    Stream.cons(2,
      (fib zip fib.tail) map {case (x, y)          


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 04:38

    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.

提交回复
热议问题