### Scala – Tail Recursion

• date 27th April, 2021 |
• by Prwatech |

The tail recursive function are effective than non tail recursive functions since tail-recursion can be enhanced by compiler. A recursive function is supposed to be tail recursive if the recursive call is the last thing done by the function. There is no reason to keep record of the past state.

tail recursion function uses a package import scala.annotation.tailrec  in the program.

use case 1:

``````// Scala program of GCD using recursion
import scala.annotation.tailrec
object prwatech {
// Function defined
def GCD(x: Int, y: Int): Int =
{
// tail recursion function defined
@tailrec def gcd(a:Int, b:Int): Int=
{
if (b == 0) a
else gcd(b, a % b)
}
gcd(y, x)
}
// Main method
def main(args:Array[String])
{
println(GCD(5, 10))
}
}``````

output:

5

use case 2:

``````// Scala program of factorial with tail recursion
import scala.annotation.tailrec
object eduprwa {
// 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(6))
}
}``````

output:

720

use case 3:

``````// Scala program of factorial with tail recursion
import scala.annotation.tailrec
object eduprwa {
// Function defined
def factorial(n: Double): Double =
{
// Using tail recursion
@tailrec def factorialAcc(acc: Double, n: Double): Double =
{
if (n <= 1)
acc
else
factorialAcc(n * acc, n - 2)
}
factorialAcc(1, n)
}
// Main method
def main(args:Array[String])
{
println(factorial(5.4))
}
}``````

output

25.70400000000001

### Quick Support  