How to do recursive loops in scala
I was wondering if there is a better way to write recursive loops in scala.
def fib(n: Int) = {
def loop(a: BigInt = 0, b: BigInt = 1, n: Int = n): BigInt = {
if(n==0) a
else loop(b, a+b, n-1)
}
loop()
}
I could write it like this
def fib(n: Int, a: BigInt = 0, b: BigInt = 1): BigInt = {
if(n==0) a
else fib(n-1, b, a+b)
}
but then a and b would be exposed and not encapsulated inside the method anymore.
Note that you can often use foldLeft
or foldRight
in such situations:
def fib(n: Int) = (1 to n).foldLeft((BigInt(0),BigInt(1)))((p,_)=>(p._2,p._1+p._2))._1
[Edit]
Another approach would be an iterator-based solution:
def fib = Iterator.iterate((0,1)){case (x,y) => (y,x+y)}.map(_._1)
This generates an infinite amount of fibonacci numbers, but you can simply take as many as you want from it, eg fib.take(10).toList
Loops have their own scopes. When you replace a loop with a recursive function you are forced to create an explicit scope (the inner method). There is no way around it. This is how it is done. Nothing wrong about it.
链接地址: http://www.djcxy.com/p/62776.html上一篇: 递归比while循环更快?
下一篇: 如何在scala中做递归循环