Thursday, March 3, 2016

Tail Call Recursion in Scala

Recursions are resource intensive and may lead to Stack overflow if processing a huge data set. Tail Recursions help convert a recursion to a simple iteration. Pure Functions comes handy because the function calls are easily replaced by their respective results using substitution model and referential transitivity. Scala is a very powerful language because of such features which help remove the side effects of functions and help define function objects. following are few examples which showcase tail recursions:

// nth fibonacci number using tail recursions
  def feb(n:Int):Int={  
    @annotation.tailrec
    def nextNum(num1: Int, num2:Int, n :Int):Int={
      if(n==0) num2+num1
      else nextNum(num2,num2+num1,n-1)
    }  
   nextNum(0,1,n-2)  
  }


// factorial function
 def factorial(n:Int):Int={
    @annotation.tailrec
    def fact(num:Int, acc:Int):Int={
      if(num<=0) acc
      else fact(num-1, num*acc)
    }  
    fact(n,1)
  }

Awaiting your comments and examples which you tried to convert a recursion to a tail recursion.

No comments:

Post a Comment