Scala program to implement tail recursion

1. Introduction

Recursion is a technique in programming where a function calls itself to solve smaller instances of a problem. Tail recursion is a specialized form of recursion where the recursive call is the last operation in the function. Scala, with its functional programming paradigm, provides first-class support for tail recursion, which is optimized by the compiler to avoid stack overflow errors, making it more efficient. In this blog post, we will implement a tail-recursive function to calculate the factorial of a number in Scala.

2. Program Steps

1. Initialize the Scala environment.

2. Define a method to calculate the factorial of a number using tail recursion.

3. Implement an inner helper function to assist with the tail recursion.

4. Test the tail-recursive factorial method by calling it with a sample number.

5. Execute the program.

3. Code Program

object TailRecursiveFactorial {
  def main(args: Array[String]): Unit = {
    // Test the tail recursive factorial method
    val number = 5
    println(s"Factorial of $number is: ${factorial(number)}")
  }

  // Tail recursive factorial method
  def factorial(n: Int): BigInt = {
    @scala.annotation.tailrec
    def factorialHelper(n: Int, accumulator: BigInt): BigInt = {
      if (n <= 1) accumulator
      else factorialHelper(n - 1, n * accumulator)
    }

    factorialHelper(n, 1)
  }
}

Output:

Factorial of 5 is: 120

Explanation:

1. The TailRecursiveFactorial object contains our main method and the tail-recursive factorial function.

2. The factorial function computes the factorial of a number using tail recursion. It takes in an integer n and returns its factorial as a BigInt.

3. Inside the factorial function, we define a helper function called factorialHelper. This helper function takes in an integer n and an accumulator to hold the result of the factorial.

4. The @scala.annotation.tailrec annotation ensures that our function is truly tail-recursive. If it's not, the compiler will raise an error.

5. If n is less than or equal to 1, we return the accumulator since the factorial of numbers less than or equal to 1 is 1. Otherwise, we make a recursive call to factorialHelper with n-1 and n * accumulator.

6. Finally, in the main method, we test our tail-recursive factorial method with the number 5 and print out the result.


Comments