liveBook · Manning

Recursion

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

An algorithm that solves a problem by invoking itself on smaller instances of the same problem.

Recursion solves a problem by having a function call itself on smaller instances of the same problem. A useful recursive design separates a base case, which stops, from a recursive case, which reduces the problem. Without a base case, execution becomes infinite recursion, much like an infinite loop. section 1.1

Fibonacci: from direct translation to practical code

The Fibonacci rule is fib(n) = fib(n - 1) + fib(n - 2), with fib(0) = 0 and fib(1) = 1. In Swift, fib2 checks n < 2 before making its two recursive calls. This version works for small values, but repeats the same calls so often that fib(50) will not finish promptly. Memoization stores completed results in a dictionary, while an iterative version avoids recursive calls altogether. section 1.1

Apply the technique with these practical checks:

  • Identify the smallest valid input and return its answer directly. section 1.1
  • Make every recursive call move toward that base case; otherwise, the function may never terminate. section 1.1
  • Remember that an iterative solution can replace any recursive technique when that implementation is clearer or more practical. section 1.6

Towers of Hanoi

With stacks representing towers, moving one disc is the base case. Moving more than one disc means recursively moving the upper discs to a temporary tower, moving the largest disc, and recursively moving the upper discs onto the destination tower. The Swift hanoi function expresses these three moves directly. section 1.5

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Develops base cases, recursive cases, repeated-work memoization, and iterative alternatives through Swift examples rather than formal proofs.
Examples
Demonstrates Fibonacci computation and Towers of Hanoi using recursive Swift functions and stack-backed towers.
What it assumes
Assumes basic Swift functions and types while teaching recursive and base-case reasoning through small algorithmic problems.
What you can do after
Build recursive Swift functions with explicit stopping conditions, recognize repeated work, and substitute memoized or iterative implementations.
How it connects
Connects recursion with base cases, memoization, iteration, stacks, Fibonacci sequence, and Towers of Hanoi.

Also explained in

Compare how 23 books explain recursion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.