Recursion and Tail Calls

Follow a recursive list sum to the case that stops it, then keep long loops from growing with tail calls.

In this lesson you build a procedure that sums a list. You follow each recursive call to the case that stops it, then move the work before the next call so the recursion becomes a tail call. A loop written this way runs ten thousand times without growing the depth of pending calls.

Read the previous lesson, Read and Handle Errors, first. Run each complete example in the Playground. Each example shows its result below the code.

Add four numbers

LISPEX
(let loop ((xs (list 1 2 3 4)) (sum 0))
  (if (null? xs)
      sum
      (loop (cdr xs) (+ sum (car xs)))))

Result

OUTPUT
10

The name loop after let lets the body call itself. This is a named let. A procedure calling itself is recursion.

Here, xs holds the items still to add. The parameter sum holds the total so far. A parameter that carries a partial result between calls is an accumulator.

CallRemaining items, xsTotal, sum
First(1 2 3 4)0
Second(2 3 4)1
Third(3 4)3
Fourth(4)6
Last()10

null? returns true for an empty list. When xs is empty, the procedure returns sum without another call. This stopping case is the base case.

Each recursive call passes (cdr xs), the list without its first item. A finite proper list therefore reaches the base case. An empty input list returns the initial total, 0.

Find the tail call

The arguments (cdr xs) and (+ sum (car xs)) are computed before the next call to loop. Its result becomes the current call's result directly. There is no addition left to perform after it returns.

A call in this position is a tail call. Lispex reuses the current call's continuation, the work that remains after the call returns. Repeated tail calls therefore keep the depth of pending calls constant.

The loop still performs work for each item. Its running time and data memory use still depend on the program and input, and resource limits still apply.

Compare two ways to sum a list

This procedure adds the first item after the recursive call returns.

LISPEX
(define (sum-list xs)
  (if (null? xs)
      0
      (+ (car xs) (sum-list (cdr xs)))))
(sum-list (list 1 2 3))

Result

OUTPUT
6

The call for (1 2 3) waits for the sum of (2 3), then adds 1. The next call waits for the sum of (3), then adds 2. These pending additions accumulate as the list grows.

Move the addition into an argument to perform it before the next call.

LISPEX
(define (sum-list xs)
  (let loop ((rest xs) (sum 0))
    (if (null? rest)
        sum
        (loop (cdr rest) (+ sum (car rest))))))
(sum-list (list 1 2 3))

Result

OUTPUT
6

As in the first example, sum is the accumulator. Each call computes the next total before calling loop. It returns the result of loop directly.

A call whose result becomes the calling procedure's result directly is in tail position. Lispex reuses the current continuation, the work remaining after that procedure returns. It does not add another pending call for each tail call. This behavior is called proper tail calls.

Repeat ten thousand times

LISPEX
(let loop ((n 10000) (acc 0))
  (if (= n 0)
      acc
      (loop (- n 1) (+ acc 1))))

Result

OUTPUT
10000

Each call decreases n and increases acc. The next call is the last action in the selected if branch. Ten thousand iterations keep the depth of pending calls constant.

The same rule applies to mutual recursion, where procedures call each other.

LISPEX
(letrec ((even-count? (lambda (n)
                        (if (= n 0) #t (odd-count? (- n 1)))))
         (odd-count? (lambda (n)
                       (if (= n 0) #f (even-count? (- n 1))))))
  (even-count? 10000))

Result

OUTPUT
#t

Each procedure returns the other's result directly. Alternating between them preserves the tail calls.

Write the same loop with do

LISPEX
(do ((rest (list 1 2 3 4) (cdr rest))
     (sum 0 (+ sum (car rest))))
    ((null? rest) sum))

Result

OUTPUT
10

Each variable has an initial value and a next value. At each step, do computes both next values using the current rest and sum. When rest is empty, it returns sum.

Lispex translates do into a recursive loop with a tail call. Omitting the result after the stopping test makes do return zero values. See Writing Conditions for the full syntax.

Try another input

Add 5 to the first example's input list. What result should it produce? Does the recursive call remain a tail call?

Answer

The result is 15. Only the input changes. The result of loop still becomes the current call's result directly.

Evaluation Order and Tail Positions lists every form that keeps a tail position and the resource limits that still apply to a loop.

For a list operation that already has a suitable procedure, use Higher-Order Procedures.

Continue to Closures That Remember Values to build a counter that remembers its count between calls.