O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required