Skip to content
Related Articles

Related Articles

Tail Recursion in Scala
  • Last Updated : 19 Jul, 2019

Recursion is a method which breaks the problem into smaller subproblems and calls itself for each of the problems. That is, it simply means function calling itself. The tail recursive functions better than non tail recursive functions because tail-recursion can be optimized by compiler. A recursive function is said to be tail recursive if the recursive call is the last thing done by the function. There is no need to keep record of the previous state.

For tail recursion function a package import scala.annotation.tailrec will be used in the program.

Syntax:

@tailrec
def FuntionName(Parameter1, Parameter2, ...): type = …

Let us understand tail recursion by examples.

Example :






// Scala program of GCD using recursion 
import scala.annotation.tailrec
  
// Creating object 
object GFG 
    // Function defined 
    def GCD(n: Int, m: Int): Int =
    {
        // tail recursion function defined 
        @tailrec def gcd(x:Int, y:Int): Int=
        
            if (y == 0) x 
            else gcd(y, x % y) 
        
        gcd(n, m)
    
      
    // Main method 
    def main(args:Array[String]) 
    
        println(GCD(12, 18)) 
    

Output:

6

As we can see in above example @tailrec is used for gcd function that is tail recursion function. By using tail recursion no need to keep record of the previous state of gcd function.

Example :




// Scala program of factorial using tail recursion 
import scala.annotation.tailrec 
    
// Creating object 
object GFG 
    // Function defined 
    def factorial(n: Int): Int =
    
        // Using tail recursion 
        @tailrec def factorialAcc(acc: Int, n: Int): Int =
        
            if (n <= 1
                acc 
            else 
                factorialAcc(n * acc, n - 1
        
        factorialAcc(1, n) 
    
        
    // Main method 
    def main(args:Array[String]) 
    
        println(factorial(5)) 
    

Output:

120

In the above code, we can use the @tailrec annotation to confirm that our algorithm is tail recursive.

If we use this annotation and our algorithm isn’t tail recursive, the compiler will complain. For instance, if we attempt to use this annotation on the above example of the factorial method, we will get the following compile-time error.

Example :




// Scala program of factorial with tail recursion 
import scala.annotation.tailrec 
    
// Creating object 
object GFG 
    // Function defined 
    @tailrec def factorial(n: Int): Int =
    
        if (n == 1
            1
        else 
            n * factorial(n - 1
    
        
    // Main method 
    def main(args:Array[String]) 
    
        println(factorial(5)) 
    

Output:

Could not optimize @tailrec annotated method factorial: it contains a recursive call not in tail position.

My Personal Notes arrow_drop_up
Recommended Articles
Page :