如何在Scala中修复我的斐波那契流 [英] How to fix my Fibonacci stream in Scala
问题描述
我定义了一个返回斐波那契流的函数,如下所示:
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) => println("%s + %s".format(x, y)); x + y}))
}
函数可以正常运行,但效率低下(请参见下面的输出)
The functions work ok but it looks inefficient (see the output below)
scala> fib take 5 foreach println
1
2
1 + 2
3
1 + 2
2 + 3
5
1 + 2
1 + 2
2 + 3
3 + 5
8
因此,函数似乎从一开始就计算第n个斐波那契数.这是正确的吗?您将如何解决?
So, it looks like the function calculates the n-th fibonacci number from the very beginning. Is it correct? How would you fix it?
推荐答案
那是因为您使用了 def
.尝试使用 val
:
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 })
基本上, def
是一种方法;在您的示例中,每次调用该方法时,每次方法调用构造一个新流时,都将调用该方法. def
和 val
之间的区别在之前已在SO上进行了覆盖,因此在此不再赘述.如果您来自Java背景,那么应该很清楚.
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.
这是关于scala的另一件事.在Java中,方法可能是递归的,但类型和值可能不是.在Scala中,值和类型都可以递归.
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.
这篇关于如何在Scala中修复我的斐波那契流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!