In this lesson, you will be given a brief introduction to recursion and go over how recursion is implemented in Scala.
We'll cover the following
Recursion
Scala’s Implementation
Implementing Recursive Functions Using match
Recursive functions play an essential role in functional programming. But what are recursive functions?
Recursive functions are functions which call themselves in their own function body. This may seem a bit strange right now, but let’s see how this works.
Recursion
Recursion is the process of breaking down an expression into smaller and smaller expressions until you’re able to use the same algorithm to solve each expression.
A recursive function is made up of an if-else expression. The if represents the base case which is the smallest possible expression on which an algorithm will run and the else represents the recursive call; when a function calls itself, it is known as a recursive call. The recursive function will keep calling itself in a nested manner without terminating the call until it is equivalent to the base case in which case the algorithm will be applied, and all the function calls will move in an outward manner, terminating before moving on to the next one, reducing themselves until they reach the original function call.
xxxxxxxxxx
def factorial(x: Int) : Int = {
if(x == 1)
1
else
x * factorial(x-1)
}
// Driver Code
print(factorial(4))
xxxxxxxxxx
/*
Recursion is when a function calls itself until someone stops it.
If no one stops it then it'll recurse (call itself) forever.
*/
// program to count down numbers to 1
function countDown(number) {
// display the number
console.log(number);
// decrease the number value
const newNumber = number - 1;
// base case
if (newNumber > 0) {
countDown(newNumber);
}
}
countDown(4);
// Out put:
4
3
2
1
xxxxxxxxxx
// Basic Recursive function
// It works in all languages but lets try with C
// lets make a greedy strlen
int my_recursive_strlen(int index, char *str) // note that index must be set at 0 to work in this case
{
if (str[index] == '\0')
return index + 1;
else
return my_recursive_strlen(index++); // i send index + 1 to next function call
// this increment index in our recursive stack
}
void main(void)
{
printf("length of Bonjour = %d\n", my_recursive_strlen(0, "bonjour"));
}
//output : length of Bonjour = 7
// Recursive functions are greedy and should be used in only special cases who need it
// or who can handle it.
// a function become recursive if she calls herself in stack
xxxxxxxxxx
>>> def sum_digits(n):
"""Return the sum of the digits of positive integer n."""
if n < 10:
return n
else:
all_but_last, last = n // 10, n % 10
return sum_digits(all_but_last) + last
xxxxxxxxxx
void recurse()
{
..
recurse();
..
}
int main()
{
..
recurse();
..
}