Scala – Recursion Functions
Recursion is a strategy that breaks the problem into more modest sub problem and calls itself for every one of the problem. That is, it essentially implies function calling itself. We can utilize recursion rather than loops. Scala upholds Recursion very well.
Recursive functions play a significant role in functional programming paradigms like Scala, where immutability and expressive code are emphasized. In Scala, a recursive function is a function that calls itself either directly or indirectly to solve a problem by breaking it down into smaller subproblems.
Key aspects of recursion in Scala include:
-
Termination Conditions: Recursive functions must have one or more termination conditions (base cases) to prevent infinite recursion. These conditions define when the recursion should stop and the function should return a result.
-
Tail Recursion: Scala supports tail call optimization (TCO), where recursive calls are optimized into efficient iterative loops. Tail-recursive functions can avoid stack overflow errors and improve performance compared to non-tail-recursive functions.
-
Immutable State: Recursive functions are well-suited for immutable data structures and functional programming principles. They facilitate a declarative style of programming by allowing developers to express computations in terms of function calls and transformations.
use case 1:
// Scala program of factorial using recursion
object prwatech {
def fact(n:Int): Int=
{
if(n == 1) 1
else n * fact(n - 1)
}
// Main method
def main(args:Array[String])
{
println(fact(4))
}
}
output:
24
use case 2:
// Scala program of GCD using recursion
// Creating object
object eduprwa {
// Function defined
def gcd(a:Int, b:Int): Int=
{
if (b == 1) a
else gcd(b, a % b)
}
// Main method
def main(args:Array[String])
{
println(gcd(10, 17))
}
}
output
3
use case 3:
// Scala program of sum all numbers
// using recursion
// Creating object
object prwa
{
// Function defined
def sum(num: Int): Int=
{
if (num == 1)
1
else
sum(num - 1) + num
}
// Main method
def main(args:Array[String])
{
println(sum(15))
}
}
output:
120
Scala – Recursion Functions