How to make 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 will be opened and not encapsulated inside the method.

+6
source share
2 answers

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 

[change]

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 number of fibonacci numbers, but you can just take as much as you want from it, for example. fib.take(10).toList

+3
source

Cycles have their own areas. When you replace a loop with a recursive function, you are forced to create an explicit scope (internal method). There is no such thing. Here's how to do it. Nothing wrong with that.

+1
source

Source: https://habr.com/ru/post/901323/


All Articles