A Simple Recursion

Recursion is used quite extensively in a number of algorithms, like quick sort, dynamic programming, stack-based operations…and the list goes on. Recursion is highly expressive and intuitive. Sometimes we also use recursion to avoid mutation. Let’s look at a use of recursion here. We’ll keep the problem simple so we can focus on the issues with recursion instead of dealing with problem or domain complexities.

ProgrammingRecursions/factorial.scala
Line 1 
def​ factorial(number: ​Int​) : BigInt = {
if​(number == 0)
1
else
number * factorial(number - 1)
}

The factorial function receives a parameter and returns a value of 1 if the parameter is zero. Otherwise, it recursively calls itself to return a product of ...

Get Pragmatic Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.