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
foldLeftorfoldRightin such situations:[Edit]
Another approach would be an iterator-based solution:
This generates an infinite amount of fibonacci numbers, but you can simply take as many as you want from it, e.g.
fib.take(10).toList