Mandroid
Mandroid

Reputation: 7524

Tail recursion implementation

In tail recursion, nothing is left to do after making the recursive call. But can that call be mixed with conditional logic?

Like, is following implementation an example of tail recursion:

def fibonacci(n:Int):Int = {
  def go(count:Int, n1: Int, n2:Int): Int = {
    if(count == n){
      n1+n2
    }else{
      val x = n2
      val y = n1+n2
      go(count+1,x,y)
    }
  }
  if(n == 1){
    0
  }else{
    if(n == 2){
      return 1
    }else{
      go(3,0,1)
    }
  }
}

Upvotes: 0

Views: 78

Answers (1)

joesan
joesan

Reputation: 15435

In a tail recursion, you could do whatever logic you want! It does not matter. What matters is that the last line of the method or to put it in other words, every place where your method returns should in fact either be a recursive call or the method should return completely out!

So basically, you treat your tail recursion as a while loop!

Have a look here for more information: Understanding the Idea behind Tail Recursion in Scala

Upvotes: 2

Related Questions