Scheme tail calls and iteration
last modified November 24, 2026 Guile 3.0
Scheme has no while or for statement in its core
syntax. Loops are written as procedures that call themselves, and the language
guarantees that such calls do not use up memory when they are made in
tail position. This guarantee, called proper tail calls,
turns recursion into iteration. This article shows how to write tail-recursive
procedures, and introduces the two loop forms built on them: the named
let and do. The examples run with GNU Guile 3.0.7.
An accumulator parameter
The factorial in the recursion article multiplied after the recursive call returned. The work can also be done before the call: an extra parameter, the accumulator, carries the product computed so far, and each call passes an updated product on.
(define (factorial-step n product)
(if (= n 0)
product
(factorial-step (- n 1) (* n product))))
(define (factorial n)
(factorial-step n 1))
(display (factorial 5))
(newline)
(display (factorial 25))
(newline)
factorial-step multiplies n into the product and then calls itself
with the smaller n. When n reaches 0, the accumulated product is the answer and
is returned unchanged. factorial hides the extra parameter by
starting the process with a product of 1. The results are the same as with the
recursive version.
$ guile accumulator.scm 120 15511210043330985984000000
An iterative process
Printing the parameters of each call shows how the accumulator version proceeds. Unlike the recursive factorial, nothing is left to do after a call returns, so the whole state of the computation is in the two parameters.
(define (factorial-step n product)
(display "n = ")
(display n)
(display ", product = ")
(display product)
(newline)
(if (= n 0)
product
(factorial-step (- n 1) (* n product))))
(display (factorial-step 4 1))
(newline)
Each line is a complete snapshot: from n and the product alone the computation could be resumed. The last call returns 24, and every earlier call simply passes that value back without further work. A procedure that evolves like this is said to generate an iterative process, even though it is written recursively. The trace in the recursion article, by contrast, had to finish four pending multiplications on the way back.
$ guile steps.scm n = 4, product = 1 n = 3, product = 4 n = 2, product = 12 n = 1, product = 24 n = 0, product = 24 24
Tail position
A call is in tail position when its value is returned directly as
the value of the procedure. Scheme implementations must execute such a call
without keeping the caller's frame, so a chain of tail calls runs in constant
space. The last expression of a body, both branches of an if, and
the last expression of a cond clause are tail positions; the
operands of + are not.
(define (sum-to n)
(if (= n 0)
0
(+ n (sum-to (- n 1)))))
(define (sum-step n total)
(if (= n 0)
total
(sum-step (- n 1) (+ total n))))
(define (collatz-steps n steps)
(cond ((= n 1) steps)
((even? n) (collatz-steps (/ n 2) (+ steps 1)))
(else (collatz-steps (+ (* 3 n) 1) (+ steps 1)))))
(display (sum-to 1000))
(newline)
(display (sum-step 1000 0))
(newline)
(display (sum-step 50000000 0))
(newline)
(display (collatz-steps 27 0))
(newline)
In sum-to, the recursive call is an operand of +, so
every call must wait. In sum-step, the call is the whole
alternative of the if, a tail position, so 50 million iterations
need no more memory than one. On the test machine, sum-to with an
argument of 10 million used about 530 MB of memory, while sum-step
with the same argument stayed at about 10 MB. collatz-steps has two
tail calls in the clauses of a cond; it counts how many steps the
Collatz rule takes to reach 1 from 27.
$ guile constant.scm 500500 500500 1250000025000000 111
Named let
Writing a separate helper procedure for every loop is tedious. A named
let defines a local procedure and calls it at once. The name comes after
let, the bindings give the initial values of the parameters, and
calling the name inside the body starts the next iteration.
(let loop ((i 1))
(when (<= i 5)
(display i)
(display " squared is ")
(display (* i i))
(newline)
(loop (+ i 1))))
(define (factorial n)
(let loop ((i n) (product 1))
(if (= i 0)
product
(loop (- i 1) (* product i)))))
(display (factorial 20))
(newline)
The first loop is called loop, a common but arbitrary name. It
starts with i bound to 1 and calls itself with (+ i
1) while i is at most 5; when the test fails,
when does nothing and the loop ends. The factorial has two loop
variables, the counter and the product, and needs no separate helper. A named
let is a shorthand for a letrec with a
lambda, like the one in the variables
and binding article.
$ guile namedlet.scm 1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16 5 squared is 25 2432902008176640000
Accumulating results
A loop can carry any number of accumulators. A list built by
cons in a loop grows at the front, so the order of the iteration
decides the order of the result.
(define (average lst)
(let loop ((rest lst) (total 0) (count 0))
(if (null? rest)
(/ total count)
(loop (cdr rest) (+ total (car rest)) (+ count 1)))))
(define (range from to)
(let loop ((i to) (result '()))
(if (< i from)
result
(loop (- i 1) (cons i result)))))
(define (countdown-list n)
(let loop ((i 1) (result '()))
(if (> i n)
result
(loop (+ i 1) (cons i result)))))
(display (average '(4 8 15 16 23 42)))
(newline)
(display (range 1 10))
(newline)
(display (countdown-list 10))
(newline)
average walks the list with three loop variables: the rest of the
list, the running total, and the count. range counts down from
to, so that the last number consed is the first one, and the list
comes out in ascending order. countdown-list counts up and
therefore produces the numbers in descending order. Unlike the recursive
range in the recursion article, both loops run in constant stack
space.
$ guile accumulate.scm 18 (1 2 3 4 5 6 7 8 9 10) (10 9 8 7 6 5 4 3 2 1)
Fibonacci as a loop
The tree-recursive Fibonacci procedure needed hundreds of thousands of calls for small arguments. As a loop, it keeps the last two numbers and moves forward one step at a time.
(define (fib n)
(let loop ((i 0) (a 0) (b 1))
(if (= i n)
a
(loop (+ i 1) b (+ a b)))))
(display (fib 10))
(newline)
(display (fib 25))
(newline)
(display (fib 100))
(newline)
(display (fib 1000))
(newline)
In each step, a takes the value of b and
b becomes the sum of the two. After n steps, a holds
the nth Fibonacci number. The loop makes n steps for argument n, so even the
thousandth Fibonacci number, a 209-digit integer, appears at once.
$ guile fibonacci.scm 55 75025 354224848179261915075 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
The do loop
do is the standard loop form. It lists variables with an initial
value and a step expression, then a test with result expressions, and then a
body. Before each iteration the test is evaluated; when it is true, the result
expressions are evaluated and the last one is the value of the loop. Otherwise
the body runs and all variables are updated by their step expressions.
(do ((i 1 (+ i 1)))
((> i 5))
(display i)
(display " "))
(newline)
(display
(do ((i 1 (+ i 1))
(sum 0 (+ sum i)))
((> i 100) sum)))
(newline)
(define (digits n)
(do ((rest n (quotient rest 10))
(count 0 (+ count 1)))
((< rest 10) (+ count 1))))
(display (list (digits 7) (digits 2026) (digits (expt 2 100))))
(newline)
The first loop prints the numbers 1 to 5. Its test clause ((> i
5)) has no result expression, so the loop is used only for its effect.
The second loop has two variables updated in parallel and returns
sum when i exceeds 100; its body is empty.
digits divides by 10 until one digit is left, counting the
divisions. 2100 has 31 digits.
$ guile doloop.scm 1 2 3 4 5 5050 (1 4 31)
Looping over a vector
do is a natural fit for vectors, whose elements are reached by
index. The loop variable runs from 0 to the length of the vector minus one.
(define size 10)
(define squares (make-vector size 0))
(do ((i 0 (+ i 1)))
((= i size))
(vector-set! squares i (* i i)))
(display squares)
(newline)
(define (vector-sum vec)
(do ((i 0 (+ i 1))
(total 0 (+ total (vector-ref vec i))))
((= i (vector-length vec)) total)))
(display (vector-sum squares))
(newline)
(define temperatures (vector 12 15 9 21 18 7 14))
(define warmest
(do ((i 1 (+ i 1))
(best (vector-ref temperatures 0) (max best (vector-ref temperatures i))))
((= i (vector-length temperatures)) best)))
(display warmest)
(newline)
The first loop fills a vector, created by make-vector with ten
zeros, with the squares of the indexes. vector-sum accumulates the
elements in a second loop variable. The step expressions are all evaluated with
the old values, so total adds the element at the current index
before i moves on. The last loop finds the warmest temperature
by keeping the larger of best and the next element.
$ guile vectors.scm #(0 1 4 9 16 25 36 49 64 81) 285 21
Nested loops
Loops nest like any other expressions. The body of an outer loop can contain an inner loop that runs completely for every iteration of the outer one.
(define (pad n)
(when (< n 10) (display " "))
(when (< n 100) (display " "))
(display n))
(define (multiplication-table size)
(do ((row 1 (+ row 1)))
((> row size))
(do ((col 1 (+ col 1)))
((> col size))
(pad (* row col))
(display " "))
(newline)))
(multiplication-table 6)
The outer do goes through the rows and the inner one through the
columns of each row. pad prints up to two spaces before a number so
that the columns line up for values below 1000. After the inner loop, a
newline ends the row.
$ guile table.scm 1 2 3 4 5 6 2 4 6 8 10 12 3 6 9 12 15 18 4 8 12 16 20 24 5 10 15 20 25 30 6 12 18 24 30 36
Leaving a loop early
A named let stops whenever a branch does not call the loop again,
so it can end as soon as the answer is known. The next program finds the
smallest divisor of a number and uses it to list primes.
(define (smallest-divisor n)
(let loop ((d 2))
(cond ((> (* d d) n) n)
((= (remainder n d) 0) d)
(else (loop (+ d 1))))))
(define (prime? n)
(and (> n 1) (= (smallest-divisor n) n)))
(define (primes-up-to limit)
(let loop ((n limit) (found '()))
(cond ((< n 2) found)
((prime? n) (loop (- n 1) (cons n found)))
(else (loop (- n 1) found)))))
(display (primes-up-to 50))
(newline)
(display (smallest-divisor 91))
(newline)
(display (prime? 1000003))
(newline)
smallest-divisor tries divisors from 2. Its cond has
two exits: when d squared exceeds n, n has no smaller divisor and is returned;
when d divides n, d is the answer. Only the third clause continues the loop.
prime? combines the test with and.
primes-up-to counts down from the limit, so the primes are collected
in ascending order. 1000003 is prime, which the loop confirms after about a
thousand trial divisions.
$ guile primes.scm (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47) 7 #t
Source
Iteration mechanisms — GNU Guile Reference Manual
R7RS: the Revised7 Report on Scheme
In this article we have rewritten recursive procedures with accumulators,
traced an iterative process, identified tail positions, written loops with the
named let and with do, iterated over vectors, nested
loops, and left a loop as soon as its answer was known. The
recursion article covers the recursive
patterns, and the pairs and lists article applies
these loops to lists.
Author
List all Scheme tutorials.