Programming Search⌘K

Conceptcore

Recursion

Also called recursive function, tail call, tail recursion, tail call elimination.

A recursive function calls itself on a smaller part of its input until it reaches a base case. Each active call needs a frame on the stack, unless a tail call is turned into a jump.

Applies to
core-languages

Idea

A recursive definition defines a thing in terms of a smaller instance of the same thing. A recursive function calls itself, directly or through other functions. Each call works on a smaller part of the problem. A base case stops the chain: for that input, the function returns an answer and makes no further call. McCarthy used this form to define functions such as the factorial in LISP. He also noted that a recursive definition does not guarantee that the computation ends.1

Recursion fits data that has a recursive shape. A list is empty, or it is an element followed by a list. A tree is a leaf, or it is a node with child trees. A function over such data has one case for each form of the data. It calls itself on each part that has the same form. In Python, total adds up the numbers in a nested list.

def total(item):
    if isinstance(item, int):
        return item
    result = 0
    for child in item:
        result += total(child)
    return result


print(total([1, [2, 3], [[4], 5]]))
Output
15

The base case is a number. The recursive case is a list: the function calls itself on each element and adds the results. The depth of nesting in the input does not matter to the code. A loop can do the same work only if it keeps a stack of its own (see Variations and related ideas).

How it works

Each call of a function needs its own copy of the parameters and the local variables. It also needs a record of the place in the caller where the work continues. Early implementations gave each subroutine one fixed working space. Dijkstra pointed out that such a subroutine cannot be called again while an earlier activation of it has not ended, because the second call overwrites the data of the first.3 His solution was a stack. Each call pushes an activation record, also called a frame. The frame holds the parameters, the local variables and the link, which is the return address in the caller. The return pops the frame. McCarthy's LISP used the same idea. Before a recursive routine calls itself, it saves the values that it still needs on a "public push-down list", and it restores them after the call.2

The trace shows the frames of factorial(3). Each line is indented by the depth of the call.

def factorial(n, depth=0):
    print("  " * depth + f"call factorial({n})")
    if n == 0:
        result = 1
    else:
        result = n * factorial(n - 1, depth + 1)
    print("  " * depth + f"return {result}")
    return result


factorial(3)
Output
call factorial(3)
  call factorial(2)
    call factorial(1)
      call factorial(0)
      return 1
    return 1
  return 2
return 6

At the deepest point, four frames are on the stack. Each frame waits for the call above it to return, because it still has a multiplication to do.

top     factorial(0)   n = 0   returns 1 to factorial(1)
        factorial(1)   n = 1   waits, then computes 1 * result
        factorial(2)   n = 2   waits, then computes 2 * result
bottom  factorial(3)   n = 3   waits, then computes 3 * result

The stack of a thread has a maximum size. A recursion whose depth grows with the input can run out of stack. The result depends on the language.

Language What happens when the stack is full Can the program recover
Python RecursionError when the depth passes sys.getrecursionlimit()11 yes, it is an exception
JavaScript (V8) RangeError: Maximum call stack size exceeded (see the JavaScript example) yes
Java, Kotlin StackOverflowError13 yes, a catch clause can catch it
C# the runtime ends the process22 no
Go the program crashes when a goroutine passes the maximum stack size19 no
Rust the process stops with a stack overflow (see the Rust example) no
C, C++ the operating system usually stops the process with a signal no

The Python limit exists to protect the interpreter. It stops infinite recursion before it overflows the C stack and crashes Python.11

Tail calls

A call is in tail position when it is the last thing that the caller does. The caller returns the result of the callee and does no more work. In n * factorial(n - 1), the multiplication runs after the call, so the call is not a tail call. In return count(n - 1, steps + 1), the caller returns the result directly, so the call is a tail call.

Steele showed that a call in tail position can be compiled as a jump.4 The frame of the caller is not needed any more, so the callee can reuse it and return straight to the caller of the caller. He wrote: "Such a call is called tail-recursive because the call appears to be recursive, but is not, since it appears at the tail end of the caller."4

each call pushes a frame               tail call compiled as a jump
count(3, 0)                            count(3, 0)
  count(2, 1)                          -> count(2, 1)   same frame
    count(1, 2)                        -> count(1, 2)   same frame
      count(0, 3) returns 3            -> count(0, 3)   returns 3 to the first caller
stack depth grows with n               stack depth stays at one frame

With this change, a tail-recursive function runs in constant stack space, like a loop. Languages give three different answers to the question "does a tail call take a frame?"

  • A guarantee. Scheme requires implementations to be properly tail-recursive. An implementation must support an unbounded number of active tail calls.5 ECMAScript defines tail position calls for strict mode code. Before such a call, the abstract operation PrepareForTailCall discards the resources of the current execution context.7 Calls in non-strict code, and calls in generator and async function bodies, are never in tail position.6
  • A guarantee for marked calls. Kotlin turns a function with the tailrec modifier into a loop.16 Clang's musttail attribute on a return statement requires the compiler to emit a tail call, even with optimization off.10
  • An optimization. GCC turns sibling and tail recursive calls into jumps with -foptimize-sibling-calls, which -O2, -O3 and -Os enable.9 The C example counts to 100,000,000 this way. The same code at -O0 can overflow the stack, so a program that depends on it is fragile.

Other implementations make a frame for each call. The JVM creates a frame each time a method is invoked.14 CPython makes a frame for each Python call, and the depth limit counts calls in tail position too (see the Python example). V8 implemented the proper tail calls of ECMAScript but did not ship them, so Node.js gives a stack overflow for a deep tail call.8

Go takes another approach to depth. A goroutine starts with a small stack. When the stack is full, the runtime allocates a larger stack and copies the frames into it.20 Deep recursion in Go therefore works up to the maximum stack size, which is 1 GB on 64-bit systems by default.19

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNative
SQLNative
BashNative
PowerShellNative
HTMLDoes not applyMarkup has no functions that can call themselves.
CSSDoes not applyStyle rules have no functions that can call themselves.
Regular expressionsAbsentThe regex dialects of ECMAScript, Python re, Go regexp and the Rust regex crate have no way for a pattern to refer to itself. Alternative: The recursive patterns of PCRE2, such as (?R), or a parser written in a general language.

Every general-purpose language in tier 1 allows a function to call itself. The differences are in the depth limit, in what happens at the limit, and in tail calls. The example files show a recursive function over a tree in each language.

Language Verdict Form
Python native a function that calls itself; a depth limit of sys.getrecursionlimit() frames
JavaScript native a function that calls itself; RangeError at the limit
TypeScript native as JavaScript; type aliases can be recursive
Java native a method that calls itself; StackOverflowError at the limit
C native a function that calls itself; no check of the depth
C++ native a function that calls itself; constexpr recursion at compile time
C# native a method or local function; a stack overflow ends the process
Go native a function that calls itself; goroutine stacks grow
Rust native an fn that calls itself; Box for recursive types
Kotlin native a function that calls itself; tailrec for loops
PowerShell native a function that calls itself
Bash native a function with local variables; FUNCNEST limits the depth
SQL native WITH RECURSIVE common table expressions
Regex absent the common dialects have no recursive patterns
HTML/CSS n/a markup and style rules have no functions

Bash functions may be recursive, and Bash places no limit on the depth by default.23 The variable FUNCNEST sets a maximum nesting level. A call past it aborts the current command.24

SQL has no recursive functions in its core, but a common table expression can refer to itself. In SQLite, the first part of the expression gives the starting rows, and the recursive part computes more rows from them. SQLite does not use a call stack. It keeps the rows in a queue and runs the recursive part on one row at a time, until the queue is empty.25

The regex dialects of ECMAScript, Python, Go and Rust have no way for a pattern to refer to itself, so they cannot match nested parentheses of any depth. PCRE2 adds recursive patterns such as (?R) for this case.27 A parser is the usual alternative.

PythonGitHub
import sys


def total(item):
    if isinstance(item, int):
        return item
    return sum(total(child) for child in item)


def depth(n):
    return 0 if n == 0 else 1 + depth(n - 1)


print(total([1, [2, 3], [[4], 5]]))
print(sys.getrecursionlimit())
print(depth(900))
try:
    depth(100_000)
except RecursionError as error:
    print(type(error).__name__, error)
Output
15
1000
900
RecursionError maximum recursion depth exceeded
  • Verdict: native. A function can call itself by name, and each call gets its own frame with its own local variables.
  • CPython limits the depth of Python calls. sys.getrecursionlimit() gives the limit, and a deeper call raises RecursionError, which a program can catch.
  • sys.setrecursionlimit() raises the limit. The highest safe value depends on the platform, and a limit that is too high can crash the interpreter.
  • A call in tail position takes a frame like any other call. The function below has its recursive call in tail position and still raises RecursionError.
  • functools.cache stores the result of each call, which removes the repeated work of tree recursion such as the naive Fibonacci function.

This code raises RecursionError, on purpose.

def count(n, steps=0):
    if n == 0:
        return steps
    return count(n - 1, steps + 1)


print(count(100_000))
#include <print>
#include <vector>

struct Node {
    int value;
    std::vector<Node> children;
};

int total(const Node& node) {
    int sum = node.value;
    for (const Node& child : node.children) {
        sum += total(child);
    }
    return sum;
}

constexpr long factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1); }

static_assert(factorial(10) == 3628800);

int main() {
    Node tree{1, {Node{2, {Node{4, {}}, Node{5, {}}}}, Node{3, {}}}};
    std::println("{}", total(tree));
    std::println("{}", factorial(20));
}
Output
15
2432902008176640000
  • Verdict: native. Functions can call themselves, and a constexpr function can recurse during constant evaluation, so static_assert checks factorial(10) at compile time.
  • The compiler limits the depth of constant evaluation. GCC sets it with -fconstexpr-depth, and the standard asks for at least 512.
  • A local object with a destructor runs code after the recursive call returns, so the call is not in tail position. Clang's musttail attribute requires that the variables in scope be trivially destructible.
  • std::vector<Node> inside Node gives a recursive type. The vector holds its elements on the heap, so the size of Node is finite.

Endless recursion in a constexpr evaluation is a compile error, not a crash at run time.

This code does not compile, on purpose.

constexpr int forever(int n) { return forever(n + 1); }

static_assert(forever(0) == 0);

int main() {}
JavaGitHub
public class Main {
    sealed interface Tree permits Leaf, Node {}

    record Leaf(int value) implements Tree {}

    record Node(Tree left, Tree right) implements Tree {}

    static int total(Tree tree) {
        return switch (tree) {
            case Leaf leaf -> leaf.value();
            case Node node -> total(node.left()) + total(node.right());
        };
    }

    static int depth(int n) {
        return n == 0 ? 0 : 1 + depth(n - 1);
    }

    public static void main(String[] args) {
        Tree tree = new Node(new Leaf(1), new Node(new Leaf(2), new Leaf(3)));
        System.out.println(total(tree));
        System.out.println(depth(1000));
        try {
            depth(100_000_000);
        } catch (StackOverflowError error) {
            System.out.println("caught " + error.getClass().getName());
        }
    }
}
Output
6
1000
caught java.lang.StackOverflowError
  • Verdict: native. A method can call itself. Each call creates a fresh frame on the stack of its thread.
  • When a thread needs more stack than the JVM permits, the JVM throws StackOverflowError. It is an Error, not an Exception, but a catch clause can still catch it.
  • The -Xss option of the java launcher sets the stack size of a thread. The default depends on the platform.
  • The JVM creates a frame each time a method is invoked, so a call in tail position also takes a frame.
  • A sealed interface with records gives a recursive data type, and a switch over it covers each case.
#include <stddef.h>
#include <stdio.h>

struct node {
    int value;
    struct node *left;
    struct node *right;
};

static int total(const struct node *tree) {
    if (tree == NULL) {
        return 0;
    }
    return tree->value + total(tree->left) + total(tree->right);
}

int main(void) {
    struct node four = {4, NULL, NULL};
    struct node five = {5, NULL, NULL};
    struct node two = {2, &four, &five};
    struct node three = {3, NULL, NULL};
    struct node one = {1, &two, &three};
    printf("%d\n", total(&one));
    return 0;
}
Output
15
  • Verdict: native. A C function can call itself, and each call gets an activation record on the stack.
  • C does not check the depth of recursion. When the stack is full, the process usually gets a signal and stops (see the last block).
  • The standard does not require tail call elimination. GCC turns sibling and tail recursive calls into jumps at -O2, -O3 and -Os. The program below counts to 100,000,000 with a tail call at -O2.
  • Clang's attribute musttail on a return statement requires the compiler to emit a tail call, even without optimization.
#include <stdio.h>

static long count(long n, long steps) {
    if (n == 0) {
        return steps;
    }
    return count(n - 1, steps + 1);
}

int main(void) {
    printf("%ld\n", count(100000000, 0));
    return 0;
}
Output
100000000

A deep recursion that is not a tail call overflows the stack. Under AddressSanitizer, the run stops with a stack-overflow report. Without the sanitizer, the process usually dies with a segmentation fault.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stdio.h>

static long depth(long n) {
    volatile long frame = n;
    if (n == 0) {
        return 0;
    }
    return depth(n - 1) + (frame > 0);
}

int main(void) {
    printf("%ld\n", depth(100000000));
    return 0;
}
static int Total(Tree tree) => tree switch
{
    Leaf leaf => leaf.Value,
    Branch branch => Total(branch.Left) + Total(branch.Right),
    _ => throw new ArgumentException("unknown tree"),
};

static int Depth(int n) => n == 0 ? 0 : 1 + Depth(n - 1);

Console.WriteLine(Total(new Branch(new Leaf(1), new Branch(new Leaf(2), new Leaf(3)))));
Console.WriteLine(Depth(1000));

abstract record Tree;
record Leaf(int Value) : Tree;
record Branch(Tree Left, Tree Right) : Tree;
Output
6
1000
  • Verdict: native. A method or a local function can call itself.
  • A stack overflow in .NET is not an exception that the program can handle. A try/catch block cannot catch StackOverflowException, and the runtime ends the process.
  • For this reason, code that recurses on input of unknown depth should check the depth itself, or use a loop with an explicit Stack<T>.

This code fails on purpose. The output below is the error.

static int Depth(int n) => n == 0 ? 0 : 1 + Depth(n - 1);

try
{
    Console.WriteLine(Depth(100_000_000));
}
catch (Exception error)
{
    Console.WriteLine("never printed: " + error.GetType().Name);
}
JavaScriptGitHub
function total(item) {
  if (typeof item === "number") return item;
  let sum = 0;
  for (const child of item) sum += total(child);
  return sum;
}

function depth(n) {
  return n === 0 ? 0 : 1 + depth(n - 1);
}

console.log(total([1, [2, 3], [[4], 5]]));
console.log(depth(5000));
try {
  depth(10_000_000);
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Output
15
5000
RangeError: Maximum call stack size exceeded
  • Verdict: native. A function declaration can call itself by its name, and a named function expression can call itself by the name inside the expression.
  • When the engine runs out of stack, it throws a RangeError. In V8, the message is "Maximum call stack size exceeded", and the program can catch the error.
  • The specification requires proper tail calls in strict mode code, but V8 does not ship them. A tail call in Node.js still takes a frame (see Pitfalls in the node).
  • The usual way around the depth limit is a loop with an explicit stack, or a trampoline.
TypeScriptGitHub
type Tree = number | Tree[];

function total(item: Tree): number {
  if (typeof item === "number") return item;
  return item.reduce((sum: number, child: Tree) => sum + total(child), 0);
}

type Json = null | boolean | number | string | Json[] | { [key: string]: Json };

function countLeaves(value: Json): number {
  if (Array.isArray(value)) return value.reduce((n: number, v: Json) => n + countLeaves(v), 0);
  if (value !== null && typeof value === "object") {
    return Object.values(value).reduce((n: number, v: Json) => n + countLeaves(v), 0);
  }
  return 1;
}

const tree: Tree = [1, [2, 3], [[4], 5]];
console.log(total(tree));
console.log(countLeaves({ name: "x", tags: ["a", "b"], size: { w: 1, h: 2 } }));
Output
15
5
  • Verdict: native. Recursive functions work as in JavaScript, and the run time behaviour is the same.
  • A type alias can refer to itself. Tree is a number or an array of trees, and Json describes any JSON value. The recursive function follows the shape of the recursive type.
  • The type checker narrows item to number after the typeof test, so each branch of the function handles one case of the type.
package main

import "fmt"

type Tree struct {
	Value    int
	Children []*Tree
}

func total(t *Tree) int {
	sum := t.Value
	for _, child := range t.Children {
		sum += total(child)
	}
	return sum
}

func depth(n int) int {
	if n == 0 {
		return 0
	}
	return 1 + depth(n-1)
}

func main() {
	tree := &Tree{1, []*Tree{{2, []*Tree{{4, nil}, {5, nil}}}, {3, nil}}}
	fmt.Println(total(tree))
	fmt.Println(depth(1_000_000))
}
Output
15
1000000
  • Verdict: native. A function can call itself, and each call gets a frame on the stack of its goroutine.
  • A goroutine starts with a small stack. When the stack is full, the runtime copies it to a larger one, so a depth of a million calls works.
  • The stack has a maximum size, 1 GB on 64-bit systems by default. A goroutine that needs more crashes the program. runtime/debug.SetMaxStack changes the maximum.

With a maximum of 1 MiB, the same depth crashes the program. The runtime prints goroutine stack exceeds 1048576-byte limit and fatal error: stack overflow, and the exit status is 2.

This code fails on purpose. The output below is the error.

package main

import (
	"fmt"
	"runtime/debug"
)

func depth(n int) int {
	if n == 0 {
		return 0
	}
	return 1 + depth(n-1)
}

func main() {
	debug.SetMaxStack(1 << 20)
	fmt.Println(depth(1_000_000))
}
RustGitHub
enum Tree {
    Leaf(i32),
    Node(Box<Tree>, Box<Tree>),
}

fn total(tree: &Tree) -> i32 {
    match tree {
        Tree::Leaf(value) => *value,
        Tree::Node(left, right) => total(left) + total(right),
    }
}

fn depth(n: u64) -> u64 {
    if n == 0 { 0 } else { 1 + depth(n - 1) }
}

fn main() {
    let tree = Tree::Node(
        Box::new(Tree::Leaf(1)),
        Box::new(Tree::Node(Box::new(Tree::Leaf(2)), Box::new(Tree::Leaf(3)))),
    );
    println!("{}", total(&tree));
    let worker = std::thread::Builder::new()
        .stack_size(256 * 1024 * 1024)
        .spawn(|| depth(1_000_000))
        .unwrap();
    println!("{}", worker.join().unwrap());
}
Output
6
1000000
  • Verdict: native. A function can call itself, and each call gets a frame on the stack of its thread.
  • A recursive type needs indirection. Tree holds its children in Box, so the compiler knows the size of Tree.
  • A spawned thread has a stack of 2 MiB by default on tier 1 platforms. thread::Builder::stack_size and the RUST_MIN_STACK variable change it. Rust does not decide the size of the main thread's stack.
  • The spawned thread above has a stack of 256 MiB, so a depth of a million calls fits.

A deep recursion on the main thread overflows the stack.

This code fails on purpose. The output below is the error.

fn depth(n: u64) -> u64 {
    if n == 0 { 0 } else { 1 + depth(n - 1) }
}

fn main() {
    println!("{}", depth(std::hint::black_box(100_000_000)));
}
KotlinGitHub
tailrec fun countDown(n: Long, steps: Long = 0): Long =
    if (n == 0L) steps else countDown(n - 1, steps + 1)

fun depth(n: Int): Int = if (n == 0) 0 else 1 + depth(n - 1)

fun main() {
    println(countDown(100_000_000))
    println(depth(1000))
    try {
        depth(100_000_000)
    } catch (error: StackOverflowError) {
        println("caught StackOverflowError")
    }
}
Output
100000000
1000
caught StackOverflowError
  • Verdict: native. A function can call itself, and on the JVM each call takes a frame, as in Java.
  • The modifier tailrec asks the compiler to turn self recursion into a loop. countDown counts to 100,000,000 with no deep stack.
  • tailrec works only when the recursive call is the last operation. It does not apply to a call with more code after it, a call inside try, catch or finally, or an open function. depth is not a tail call, because the addition runs after the call returns.
CREATE TABLE employee (name TEXT PRIMARY KEY, boss TEXT);
INSERT INTO employee VALUES
    ('Ada', NULL), ('Brian', 'Ada'), ('Chen', 'Ada'), ('Dana', 'Brian'), ('Eve', 'Dana');

WITH RECURSIVE chain(name, level) AS (
    SELECT name, 0 FROM employee WHERE boss IS NULL
    UNION ALL
    SELECT employee.name, chain.level + 1
    FROM employee JOIN chain ON employee.boss = chain.name
)
SELECT level, name FROM chain ORDER BY level, name;

WITH RECURSIVE factorial(n, value) AS (
    SELECT 1, 1
    UNION ALL
    SELECT n + 1, value * (n + 1) FROM factorial WHERE n < 10
)
SELECT value FROM factorial WHERE n = 10;
Output
0|Ada
1|Brian
1|Chen
2|Dana
3|Eve
3628800
  • Verdict: native. WITH RECURSIVE defines a table in terms of itself. The example runs in SQLite.
  • A recursive common table expression is a compound select. The first part gives the starting rows, and the recursive part refers to the table once and computes more rows from them.
  • SQLite does not use a call stack for this. It puts rows in a queue, takes one row at a time, and runs the recursive select on that row. The recursion stops when the queue is empty.
  • A recursive part with no stop condition runs until it fills memory. A WHERE clause in the recursive part or a LIMIT on the query stops it.
BashGitHub
hanoi() {
    local n=$1 from=$2 to=$3 via=$4
    (( n == 0 )) && return
    hanoi $(( n - 1 )) "$from" "$via" "$to"
    echo "move disk $n from $from to $to"
    hanoi $(( n - 1 )) "$via" "$to" "$from"
}

factorial() {
    local n=$1 rest
    if (( n <= 1 )); then
        echo 1
        return
    fi
    rest=$(factorial $(( n - 1 )))
    echo $(( n * rest ))
}

hanoi 3 A C B
factorial 10
Output
move disk 1 from A to C
move disk 2 from A to B
move disk 1 from C to B
move disk 3 from A to C
move disk 1 from B to A
move disk 2 from B to C
move disk 1 from A to C
3628800
  • Verdict: native. A shell function may call itself, and local gives each call its own variables.
  • A function returns only an exit status. A value comes back through standard output and a command substitution, which runs the function in a subshell, or through a global variable.
  • By default, Bash places no limit on the depth of recursion. The variable FUNCNEST sets a maximum nesting level, and a call beyond it aborts the command.
PowerShellGitHub
function Get-Total($Item) {
    if ($Item -is [int]) {
        return $Item
    }
    $sum = 0
    foreach ($child in $Item) {
        $sum += Get-Total $child
    }
    $sum
}

function Get-Factorial([int]$N) {
    if ($N -le 1) {
        return 1
    }
    $N * (Get-Factorial ($N - 1))
}

Get-Total @(1, @(2, 3), @(@(4), 5))
Get-Factorial 10
Output
15
3628800
  • Verdict: native. A function can call itself by name, and each call gets its own scope for its variables.
  • A function call in PowerShell does much more work than a call in a compiled language, so keep recursion shallow.
  • A function writes every value that it does not capture to its output. A recursive function must keep stray values out of the output, or the caller gets them too.
  • Mutual recursion. Two or more functions call each other, as in a recursive descent parser, where the rule for an expression calls the rule for a term and the term calls the expression again inside parentheses. The stack grows in the same way as for direct recursion.
  • Structural and generative recursion. Structural recursion follows the shape of the data, as total does, and it ends when the data ends. Generative recursion computes other subproblems from the input, as quicksort or Euclid's algorithm do. Its termination needs a separate argument, because a recursive definition alone does not guarantee that the computation ends.1
  • Accumulators. An extra parameter carries the partial result, so the work happens before the call and the call can be in tail position. count(n, steps) in the C and Kotlin examples has this form.
  • An explicit stack. A loop and a list that holds the work still to do replace the call stack. The list lives on the heap, so the depth of the input is limited only by memory.
def total(item):
    result = 0
    stack = [item]
    while stack:
        item = stack.pop()
        if isinstance(item, int):
            result += item
        else:
            stack.extend(item)
    return result


deep = 1
for _ in range(100_000):
    deep = [deep]
print(total(deep))
print(total([1, [2, 3], [[4], 5]]))
Output
1
15
  • Trampolines. A function returns a description of the next call instead of making it, and a loop runs the calls one after the other. This gives constant stack depth in a language without tail call elimination (see Pitfalls).
  • Memoization. A cache keeps the result of each call. It removes repeated work when the same subproblem comes up many times. Python's functools.cache wraps a function in a dictionary lookup on its arguments.12 Dynamic programming fills the same table in a loop, from the small subproblems to the large ones.
  • Recursive types. A type that contains itself needs indirection in languages with value types. In Rust, Box puts the child on the heap, so the compiler can compute the size of the type.18 TypeScript type aliases, Java records and C# records can also refer to themselves.
  • Recursion at compile time. A C++ constexpr function can recurse during constant evaluation. The compiler limits the depth: GCC uses -fconstexpr-depth, and the standard asks for at least 512 levels.26
  • Recursive generators. A generator that walks a tree can delegate to a generator for each child. It gives the elements one at a time instead of building a list (see Iterator).

Pitfalls

No base case, or a base case that the input never reaches

Each recursive call must move closer to a base case. Here the function steps by 2 and tests only for zero. An odd argument skips zero and never stops.

This code raises RecursionError, on purpose.

def countdown(n):
    if n == 0:
        return "done"
    return countdown(n - 2)


print(countdown(5))

The run stops with RecursionError: maximum recursion depth exceeded. In C, the same mistake overflows the stack and the process dies with a signal. The fix is a base case that covers every input that ends the recursion, here n <= 0.

def countdown(n):
    if n <= 0:
        return "done"
    return countdown(n - 2)


print(countdown(5))
Output
done

Deep input overflows the stack

A recursive function can be correct and still fail on large input, because the depth of the recursion grows with the size of the data. A linked list of a million cells needs a million frames.

This code raises StackOverflowError, on purpose.

public class Main {
    record Cell(int value, Cell next) {}

    static long sum(Cell list) {
        return list == null ? 0 : list.value() + sum(list.next());
    }

    public static void main(String[] args) {
        Cell list = null;
        for (int i = 1; i <= 1_000_000; i++) {
            list = new Cell(i, list);
        }
        System.out.println(sum(list));
    }
}

The JVM throws StackOverflowError. A larger stack with -Xss moves the limit but does not remove it.15 The fix for a list is a loop. For a tree whose depth the program does not control, the fix is an explicit stack, as in Variations and related ideas.

public class Main {
    record Cell(int value, Cell next) {}

    static long sum(Cell list) {
        long result = 0;
        for (Cell cell = list; cell != null; cell = cell.next()) {
            result += cell.value();
        }
        return result;
    }

    public static void main(String[] args) {
        Cell list = null;
        for (int i = 1; i <= 1_000_000; i++) {
            list = new Cell(i, list);
        }
        System.out.println(sum(list));
    }
}
Output
500000500000

A tail call still takes a frame

A function in accumulator form looks safe, because the recursive call is in tail position. The ECMAScript specification requires such calls in strict mode code to discard the frame of the caller.7 V8 does not ship this, so Node.js still overflows.8

This code raises RangeError, on purpose.

"use strict";

function count(n, steps) {
  if (n === 0) return steps;
  return count(n - 1, steps + 1);
}

console.log(count(1_000_000, 0));

A trampoline gives constant depth with no help from the engine. The function returns a closure for the next step, and a loop calls the closures until a value comes back.

function count(n, steps) {
  if (n === 0) return steps;
  return () => count(n - 1, steps + 1);
}

function trampoline(result) {
  while (typeof result === "function") result = result();
  return result;
}

console.log(trampoline(count(1_000_000, 0)));
Output
1000000

CPython and the JVM behave like Node.js here: each call takes a frame.14 In Kotlin, mark the function tailrec. In other languages, write the loop.

A call that looks like a tail call is not one

A call is a tail call only if nothing runs after it. These calls are not in tail position:

  • return 1 + depth(n - 1), because the addition runs after the call.
  • A call inside a try block with a finally clause, because the finally clause runs after the call. Kotlin does not allow tailrec on a call inside try, catch or finally.16
  • A call in a C++ function that has a local object with a destructor, because the destructor runs after the call. Clang's musttail requires that every variable in scope be trivially destructible.10

With GCC, the change is only an optimization. A call that is not in tail position stays an ordinary call, and the program still compiles.9

Tree recursion repeats work

A function that makes two recursive calls can do an exponential amount of work when the calls share subproblems. The naive Fibonacci function computes fib(23) twice, fib(22) three times, and so on.

This code runs but gives a wrong answer on purpose.

calls = 0


def fib(n):
    global calls
    calls += 1
    return n if n < 2 else fib(n - 1) + fib(n - 2)


print(fib(25), calls)
Output
75025 242785

The answer is right, but the function makes almost 250,000 calls. With functools.cache, each value is computed once.12

from functools import cache

calls = 0


@cache
def fib(n):
    global calls
    calls += 1
    return n if n < 2 else fib(n - 1) + fib(n - 2)


print(fib(25), calls)
Output
75025 26

Cost

  • Time per call. A call pushes a frame, jumps to the function and later returns. A loop iteration does none of this. In an interpreter such as CPython or PowerShell, a call does more work than in compiled code.
  • Stack space. The space is the depth of the recursion times the size of a frame. The default thread stack of the java launcher is 1024 KB on Linux x64 and 2048 KB on macOS AArch64.15 A Rust thread made with std::thread has 2 MiB on tier 1 platforms, and Rust does not set the size of the main thread's stack.17 CPython stops at sys.getrecursionlimit() frames, which is 1000 in the Python example.
  • Growable stacks. Go starts each goroutine with a small stack and copies the frames to a larger stack when it is full.20 A deep recursion therefore pays for the copies, but a shallow goroutine uses little memory.
  • Tail calls. When the implementation turns tail calls into jumps, a tail-recursive function uses constant stack space. The cost is in debugging: the frames that the jumps remove are missing from the stack trace. This was one of V8's reasons not to ship proper tail calls.8
  • Repeated subproblems. Tree recursion with shared subproblems takes exponential time. A cache makes it linear in the number of distinct arguments, at the cost of memory for the cache.12

History

  • 1960. John McCarthy described LISP. Conditional expressions let him define functions recursively, and the implementation saved values on a public push-down list around each recursive call.12
  • 1960. Edsger W. Dijkstra published "Recursive Programming". It described a stack of activation records with a link to the caller, so that an ALGOL 60 procedure could call itself.3
  • 1977. Guy L. Steele Jr. argued that a procedure call in tail position is a jump that passes arguments, so it needs no extra stack.4
  • 1998. William Clinger gave a formal definition of proper tail recursion. The Scheme report cites this paper for its requirement that implementations be properly tail-recursive.5
  • 2014. Go 1.4, released on 10 December 2014, replaced segmented goroutine stacks with contiguous stacks that the runtime copies when they grow.2021
  • 2015 and 2016. ES2015 specified that calls in tail position in strict mode code never cause a stack overflow. In 2016, the V8 team reported that it had implemented proper tail calls but had not shipped them.8

References

  1. John McCarthy, Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I, Communications of the ACM 3(4), 1960, pages 184 to 195, section 2d, Recursive Function Definitions
  2. John McCarthy, Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I, Communications of the ACM 3(4), 1960, pages 184 to 195, section 4e, Representation of S-Functions by Programs (the public push-down list, SAVE and UNSAVE)
  3. E. W. Dijkstra, Recursive Programming, Numerische Mathematik 2, 1960, pages 312 to 318 (open copy as CWI report MR 33, https://ir.cwi.nl/pub/9253), the sections The Aim, The Stack and The Link
  4. Guy L. Steele Jr., Debunking the "Expensive Procedure Call" Myth, MIT AI Memo 443, October 1977, section A, Procedure Calls as GOTO Statements
  5. Revised7 Report on the Algorithmic Language Scheme, 3.5 Proper tail recursion, and reference [6] (Clinger 1998)
  6. ECMA-262, ECMAScript 2026 Language Specification, 15.10.1 Static Semantics, IsInTailPosition
  7. ECMA-262, ECMAScript 2026 Language Specification, 15.10.3 PrepareForTailCall
  8. V8 blog, ES2015, ES2016, and beyond, 29 April 2016, Proper tail calls
  9. Using the GNU Compiler Collection, Options That Control Optimization, -foptimize-sibling-calls
  10. Clang documentation, Attributes in Clang, musttail
  11. The Python Standard Library, sys, Python 3.14, sys.setrecursionlimit
  12. The Python Standard Library, functools, Python 3.14, functools.cache
  13. The Java Virtual Machine Specification, Java SE 25 Edition, 2.5.2 Java Virtual Machine Stacks
  14. The Java Virtual Machine Specification, Java SE 25 Edition, 2.6 Frames
  15. The java Command, Java SE 25, Extra Options for Java, -Xss size
  16. Kotlin documentation, Functions, Tail recursive functions
  17. The Rust Standard Library, Module std::thread, Stack size
  18. The Rust Programming Language, Using Box<T> to Point to Data on the Heap, Enabling Recursive Types with Boxes
  19. Go standard library, package runtime/debug, func SetMaxStack
  20. Go 1.4 Release Notes, Changes to the runtime
  21. Go release history, go1.4 (released 2014-12-10)
  22. .NET API reference, StackOverflowException Class, Remarks
  23. Bash Reference Manual, 3.3 Shell Functions
  24. Bash Reference Manual, 5.2 Bash Variables, FUNCNEST
  25. SQLite documentation, The WITH Clause, 3. Recursive Common Table Expressions
  26. Using the GNU Compiler Collection, Options Controlling C++ Dialect, -fconstexpr-depth
  27. PCRE2 documentation, pcre2pattern, RECURSIVE PATTERNS

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/DB5SC0/text.yaml