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.
Let’s look at recursive calls as boxes within boxes.
1 of 8
Scala’s Implementation
The implementation of factorials is a very famous recursive problem. A factorial of a number is achieved by multiplying all consecutive numbers starting from 1 till the number in question. So, the factorial of 4 (represented as 4!) is equivalent to 1 x 2 x 3 x 4 = 24.
Let’s look at how we would implement this in Scala.