liveBook · Manning

Recursion

As explained in Functional Programming in Scala, Second Edition

Recursion is a technique in which a computation solves a problem by calling itself on smaller or simpler inputs.

Recursion expresses a loop without mutation: a function calls itself with a smaller or simpler state until a base case returns a value. section 2.7

Factorial as a functional loop

A factorial function can contain a local helper named go. Its parameters hold the remaining input and accumulated result. Each recursive call advances the state with go(n - 1, n * acc); when n <= 0, the helper returns acc without another call. section 2.3.1

def factorial(n: Int): Int =
  def go(n: Int, acc: Int): Int =    #1
    if n <= 0 then acc
    else go(n - 1, n * acc)
 
  go(n, 1)

Read the helper as a loop: the base case exits, while the recursive branch supplies the next state. section 2.3.1

Use these checks when reading or designing a recursive function:

  • Identify the state carried between calls. section 2.3.1
  • Find the base case that returns without recursion. section 2.3.1
  • Check whether the recursive call is in tail position, with no work left afterward. section 2.3.1
  • Trace calls manually to follow evaluation and changing values. section 2.3.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains helper state, base cases, execution traces, tail position, and tail call elimination through factorial.
Examples
Uses factorial, a recursive helper named go, and indented or flat execution traces for factorial(5).
What it assumes
Uses Scala functions, nested definitions, parameters, conditionals, and returned expression values.
What you can do after
Build recursive Scala loops, trace their evaluation, and recognize when tail recursion prevents stack growth.
How it connects
Connects recursion to loops, tail recursion, local functions, higher-order functions, and polymorphic functions.

Also explained in

Compare how 23 books explain recursion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.