ZetCode

Scheme recursion

last modified November 24, 2026 Guile 3.0

A procedure is recursive when it calls itself. Scheme has no loop statements in its core; repetition is expressed by recursion, and the language is designed to make it efficient. A recursive procedure solves a problem by reducing it to a smaller instance of the same problem until it reaches a base case that is answered directly. This article shows the common shapes of recursion. The examples run with GNU Guile 3.0.7.

Factorial

The factorial of n is the product of the numbers from 1 to n, and 0! is 1. The definition is itself recursive: n! equals n times (n − 1)!. The procedure follows it word for word.

factorial.scm
(define (factorial n)
  (if (= n 0)
      1
      (* n (factorial (- n 1)))))

(display (factorial 5))
(newline)
(display (factorial 20))
(newline)
(display (factorial 30))
(newline)

The if separates the base case, n equal to 0, from the recursive case, which multiplies n by the factorial of n − 1. Each call works on a smaller number, so the recursion ends. Scheme integers grow as needed, which is why 30! is printed in full instead of overflowing.

$ guile factorial.scm
120
2432902008176640000
265252859812191058636308480000000

Tracing the calls

Each recursive call waits for the result of the next one before it can finish its multiplication. Adding a depth parameter and printing on the way in and on the way out makes this chain of pending calls visible.

trace.scm
(define (indent depth)
  (display (make-string (* 2 depth) #\space)))

(define (factorial n depth)
  (indent depth)
  (display "factorial ")
  (display n)
  (newline)
  (let ((result (if (= n 0)
                    1
                    (* n (factorial (- n 1) (+ depth 1))))))
    (indent depth)
    (display "=> ")
    (display result)
    (newline)
    result))

(factorial 4 0)

indent prints two spaces per level, using make-string to build the padding. The calls descend to factorial 0, which returns 1 without calling itself. Then the pending calls complete in reverse order, each multiplying the returned value by its own n. The let keeps the result so that it can be printed and returned.

$ guile trace.scm
factorial 4
  factorial 3
    factorial 2
      factorial 1
        factorial 0
        => 1
      => 1
    => 2
  => 6
=> 24

Recursion over lists

A list is either empty or a pair of a first element and the rest of the list. This definition gives the shape of most list procedures: the empty list is the base case, and the recursive case handles car and recurses on cdr.

listsum.scm
(define (list-sum lst)
  (if (null? lst)
      0
      (+ (car lst) (list-sum (cdr lst)))))

(define (count-items lst)
  (if (null? lst)
      0
      (+ 1 (count-items (cdr lst)))))

(define (largest lst)
  (if (null? (cdr lst))
      (car lst)
      (max (car lst) (largest (cdr lst)))))

(define numbers '(4 8 15 16 23 42))

(display (list (list-sum numbers) (count-items numbers) (largest numbers)))
(newline)
(display (list (list-sum '()) (count-items '())))
(newline)

list-sum adds the first element to the sum of the rest, and the sum of the empty list is 0. count-items ignores the elements and adds 1 for each pair, which is how length works. largest has a different base case, a list with one element, because the empty list has no largest element. The procedures are named so as not to replace the built-in length and max.

$ guile listsum.scm
(108 6 42)
(0 0)

Building lists

A recursive procedure can also produce a list. The recursive case puts one new element in front of the list built by the recursive call, using cons, and the base case returns the empty list.

building.scm
(define (range from to)
  (if (> from to)
      '()
      (cons from (range (+ from 1) to))))

(define (squares lst)
  (if (null? lst)
      '()
      (cons (* (car lst) (car lst))
            (squares (cdr lst)))))

(define (keep-even lst)
  (cond ((null? lst) '())
        ((even? (car lst))
         (cons (car lst) (keep-even (cdr lst))))
        (else (keep-even (cdr lst)))))

(display (range 1 10))
(newline)
(display (squares (range 1 10)))
(newline)
(display (keep-even (range 1 10)))
(newline)
(display (range 5 1))
(newline)

range builds the numbers from from to to, and returns the empty list when the range is empty. squares maps each element to its square and keeps the order. keep-even uses cond with three cases: the end of the list, an element to keep, and an element to skip. The procedures can be combined, as in (squares (range 1 10)).

$ guile building.scm
(1 2 3 4 5 6 7 8 9 10)
(1 4 9 16 25 36 49 64 81 100)
(2 4 6 8 10)
()

Tree recursion

A procedure that calls itself more than once per call performs tree recursion. The Fibonacci numbers are the classic example: each number is the sum of the two before it. A top-level counter, updated with set!, records how many calls the computation takes.

fibonacci.scm
(define calls 0)

(define (fib n)
  (set! calls (+ calls 1))
  (if (< n 2)
      n
      (+ (fib (- n 1)) (fib (- n 2)))))

(define (report n)
  (set! calls 0)
  (let ((value (fib n)))
    (display "fib ")
    (display n)
    (display " = ")
    (display value)
    (display ", calls: ")
    (display calls)
    (newline)))

(report 5)
(report 10)
(report 20)
(report 25)

fib follows the mathematical definition, with 0 and 1 as base cases. The definition is clear but wasteful: (fib 25) computes the same smaller values again and again and needs almost a quarter of a million calls. The number of calls grows exponentially with n. The tail calls and iteration article computes the same numbers with a loop that makes one step per number.

$ guile fibonacci.scm
fib 5 = 5, calls: 15
fib 10 = 55, calls: 177
fib 20 = 6765, calls: 21891
fib 25 = 75025, calls: 242785

Mutual recursion

Two procedures are mutually recursive when each one calls the other. A number is even if it is 0 or if the number one smaller is odd, and odd if it is not 0 and the number one smaller is even.

mutual.scm
(define (is-even? n)
  (if (= n 0)
      #t
      (is-odd? (- n 1))))

(define (is-odd? n)
  (if (= n 0)
      #f
      (is-even? (- n 1))))

(display (list (is-even? 10) (is-odd? 10) (is-even? 7) (is-odd? 7)))
(newline)

is-even? calls is-odd?, which is defined after it. This is allowed because the name is looked up when the procedure runs, not when it is defined, and by then both definitions exist. The built-in even? and odd? are of course much faster; the example shows only the structure.

$ guile mutual.scm
(#t #f #f #t)

Nested lists

A list may contain other lists, which makes it a tree. A procedure that walks a tree recurses into both the car and the cdr of each pair, and treats anything that is not a pair as a leaf.

nested.scm
(define (count-leaves tree)
  (cond ((null? tree) 0)
        ((pair? tree)
         (+ (count-leaves (car tree))
            (count-leaves (cdr tree))))
        (else 1)))

(define (tree-depth tree)
  (cond ((null? tree) 0)
        ((pair? tree)
         (max (+ 1 (tree-depth (car tree)))
              (tree-depth (cdr tree))))
        (else 0)))

(define data '(1 (2 3) ((4) 5) (((6)))))

(write data)
(newline)
(display (list (count-leaves data) (tree-depth data)))
(newline)

count-leaves adds the leaves of the first element to those of the rest, so it counts the six numbers at every level of nesting. tree-depth adds 1 when it descends into an element and takes the larger of the two depths. The outermost list counts as one level, so the 6, nested in three more lists, lies at depth 4.

$ guile nested.scm
(1 (2 3) ((4) 5) (((6))))
(6 4)

Flattening a tree

Flattening turns a nested list into a flat list of its leaves in order. A helper procedure with an extra parameter, the list of leaves found so far to the right, does it without joining lists.

flatten.scm
(define (flatten-onto tree rest)
  (cond ((null? tree) rest)
        ((pair? tree)
         (flatten-onto (car tree) (flatten-onto (cdr tree) rest)))
        (else (cons tree rest))))

(define (flatten tree)
  (flatten-onto tree '()))

(write (flatten '(1 (2 3) ((4) 5) (((6))))))
(newline)
(write (flatten '((a b) (c (d e)) f)))
(newline)
(write (flatten '(((())))))
(newline)

flatten-onto first flattens the cdr onto rest, and then flattens the car onto that result, so the leaves end up in their original order. A leaf is added with cons, and an empty list adds nothing, which is why the last tree, made only of empty lists, flattens to (). flatten starts the process with an empty list.

$ guile flatten.scm
(1 2 3 4 5 6)
(a b c d e f)
()

Towers of Hanoi

The Towers of Hanoi puzzle moves a stack of disks from one peg to another, one disk at a time, never placing a larger disk on a smaller one. The recursive solution is short: move n − 1 disks out of the way, move the largest disk, and move the n − 1 disks on top of it.

hanoi.scm
(define moves 0)

(define (move-disk disk from to)
  (set! moves (+ moves 1))
  (display "disk ")
  (display disk)
  (display ": ")
  (display from)
  (display " -> ")
  (display to)
  (newline))

(define (hanoi n from to spare)
  (when (> n 0)
    (hanoi (- n 1) from spare to)
    (move-disk n from to)
    (hanoi (- n 1) spare to from)))

(hanoi 3 'A 'C 'B)
(display "moves: ")
(display moves)
(newline)

hanoi uses when, because there is nothing to do for zero disks. The two recursive calls swap the roles of the pegs: the first one uses the target as the spare, the second one the source. move-disk prints each move and counts it. Three disks need 7 moves; in general n disks need 2n − 1.

$ guile hanoi.scm
disk 1: A -> C
disk 2: A -> B
disk 1: C -> B
disk 3: A -> C
disk 1: B -> A
disk 2: B -> C
disk 1: A -> C
moves: 7

Halving the problem

A recursion is faster when each step reduces the problem by more than one. To raise a number to the power n, the straightforward recursion multiplies n times. Fast exponentiation squares the result for half the exponent when n is even, so it needs only about log2(n) steps.

fastpower.scm
(define (slow-power base n)
  (if (= n 0)
      1
      (* base (slow-power base (- n 1)))))

(define (square x) (* x x))

(define (fast-power base n)
  (cond ((= n 0) 1)
        ((even? n) (square (fast-power base (quotient n 2))))
        (else (* base (fast-power base (- n 1))))))

(display (slow-power 3 20))
(newline)
(display (fast-power 3 20))
(newline)
(display (fast-power 2 200))
(newline)

slow-power makes 20 recursive calls for the exponent 20. fast-power computes 320 from 310, that from 35, and so on, so it needs only a handful of calls. The odd case reduces the exponent by one to make it even. Both give the same result, and 2200 takes only a few steps.

$ guile fastpower.scm
3486784401
3486784401
1606938044258990275541962092341162602522202993782792835301376

Recursion depth

Every pending call occupies memory until it returns, so a recursion that is n levels deep needs memory proportional to n. Many languages limit the depth to a few thousand calls. Guile grows its stack as needed, so the limit is the available memory.

depth.scm
(define (sum-to n)
  (if (= n 0)
      0
      (+ n (sum-to (- n 1)))))

(display (sum-to 100))
(newline)
(display (sum-to 100000))
(newline)
(display (sum-to 1000000))
(newline)

sum-to is not tail recursive: each call still has to add n after the recursive call returns, so the third call keeps a million calls pending at once. Guile handles this depth without complaint. A much deeper recursion would eventually exhaust memory. The tail calls and iteration article shows how to write such procedures so that they run in constant space.

$ guile depth.scm
5050
5000050000
500000500000

Source

Stack overflow — GNU Guile Reference Manual

R7RS: the Revised7 Report on Scheme

In this article we have written recursive procedures with base cases, traced the calls of factorial, processed and built lists, measured the cost of tree recursion, defined mutually recursive procedures, walked and flattened nested lists, solved the Towers of Hanoi, halved a problem with fast exponentiation, and looked at recursion depth. The tail calls and iteration article turns recursion into loops, and the procedures article covers the forms of parameter lists.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.