如何在 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屋!