Conceptcore
Recursive type
Also called recursive data type, inductive data type, self-referential type, recursively defined type, recursive type alias.
A recursive type refers to itself in its own definition, as a list node refers to the next node. Lists, trees and expression trees are recursive types.
- Applies to
- core-languages
Idea
Some data contains smaller data of the same kind. A list is empty, or it is a first item followed by a shorter list. A tree is a value with a list of smaller trees. A type that describes such data must mention itself. Wikipedia says that "a recursive data type is a data type whose definition contains values of the same type".1
from dataclasses import dataclass
@dataclass
class Tree:
value: int
children: list["Tree"]
def total(t: Tree) -> int:
return t.value + sum(total(c) for c in t.children)
def depth(t: Tree) -> int:
return 1 + max((depth(c) for c in t.children), default=0)
tree = Tree(1, [Tree(2, [Tree(4, [])]), Tree(3, [])])
print("total:", total(tree))
print("depth:", depth(tree))
total: 10
depth: 3
The type Tree has a field whose type is a list of Tree. The functions that walk the data follow the shape of the type: a function on a tree calls itself on each child (see Recursion). The recursion stops at a tree with no children.
How it works
A base case and a recursive case. A useful recursive type has at least one case that does not contain the type, or the values could never end. A list has the empty list. The natural numbers of Peano arithmetic have zero: in Haskell, data Nat = Zero | Succ Nat.1 So most recursive types are sum types with a base case and one or more recursive cases (see Sum types).
Indirection. A value cannot contain a full copy of a value of its own type, because its size would be infinite. The Rust book explains: "Rust needs to know at compile time how much space a type takes up. However, the nesting of values of recursive types could theoretically continue infinitely".2 So the recursive field is a pointer or a reference:
- In C, a struct holds a pointer to its own type. The C standard shows
struct tnode { int count; struct tnode *left, *right; };, "a structure that contains an integer and two pointers to objects of the same type".3 - Go forbids a struct that contains itself directly: "A struct type T may not contain a field of type T", and the same holds through arrays and other structs.4 A pointer field, such as
next *Node, is allowed. - Rust uses
Box<T>: "Because boxes have a known size, we can enable recursive types by inserting a box in the recursive type definition."2 - Swift marks a recursive enum case with
indirect, "which tells the compiler to insert the necessary layer of indirection".5 - In Java, C#, Python, JavaScript and most functional languages, a field of a class type already holds a reference, so a type can refer to itself with no extra syntax.
Recursive type aliases. A type alias can also refer to itself, when the reference is inside another type. TypeScript 3.7 relaxed its rules so that aliases such as type Json = string | number | boolean | null | { [property: string]: Json } | Json[] are allowed.6 Python added the type statement for type aliases: "The type statement is new in Python 3.12."7 The docs note that it "natively supports forward references", so an alias can use its own name, as in type Tree = int | list[Tree].7
Theory. "In type theory, a recursive type has the general form μα.T where the type variable α may appear in the type T and stands for the entire type itself."1 For example, the natural numbers are μα. 1 + α: a value is zero (the unit) or the successor of another natural number. There are "two forms of recursive types: the so-called isorecursive types, and equirecursive types".1 With isorecursive types, the program moves between the type and its one-step unrolling with explicit operations. With equirecursive types, the two are the same type. Wikipedia notes that "equirecursive types contribute significantly more complexity to a type system than isorecursive types do".1 Wikipedia notes that "In functional programming languages, isorecursive types (in the guise of datatypes) are common too."1 There, the constructors do the rolling and the pattern matches do the unrolling.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Idiom | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | A class or a sealed interface can have properties of its own type, such as a Cons class with a tail of the list type. No example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Idiom | A table can have a foreign key to itself, and a recursive common table expression walks the rows; no example file because the examples use the core languages. |
| Bash | Does not apply | Bash has no types that can refer to themselves. |
| PowerShell | Idiom | An object property can hold another object of the same shape, so nested hashtables or custom objects form lists and trees; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | Markup has no types; a document is a tree of elements. |
| CSS | Does not apply | Style rules have no types. |
| Regular expressions | Does not apply | A pattern has no types. |
The example files define a linked list of integers, build the list 1, 2, 3, and walk it with a recursive function.
| Language | Verdict | Form |
|---|---|---|
| Python | native | a class whose field refers to the class, written as a string or with deferred annotations; a type alias7 |
| JavaScript | idiom | objects whose properties refer to other objects; no types to declare |
| TypeScript | native | a recursive interface or type alias6 |
| Java | native | a class or record whose field has its own type |
| C | native | a struct with a pointer to its own type3 |
| C++ | native | a class with a pointer or a std::unique_ptr to its own type |
| C# | native | a class or record whose field has its own type |
| Go | native | a struct with a pointer to its own type4 |
| Rust | native | an enum or a struct with a Box, Rc or reference to its own type2 |
| Kotlin | native | a class or a sealed interface whose cases refer to it |
| PowerShell | idiom | objects whose properties refer to other objects |
| Bash | n/a | Bash has no types that can refer to themselves |
| SQL | idiom | a table with a foreign key to itself, and a recursive common table expression to walk it |
| Regex | n/a | a pattern has no types |
| HTML/CSS | n/a | markup has no types; an HTML document is a tree of elements |
Haskell and ML. A data declaration can refer to the type that it declares, as in data List a = Nil | Cons a (List a). The Haskell report defines data declarations in section 4.2.1.8 Two types can also refer to each other: Wikipedia shows data Tree a = Empty | Node (a, Forest a) with data Forest a = Nil | Cons (Tree a) (Forest a).1 In Standard ML, the keyword and joins the two definitions.1
type IntList = tuple[int, IntList] | None
def total(xs: IntList) -> int:
match xs:
case None:
return 0
case (head, tail):
return head + total(tail)
def length(xs: IntList) -> int:
return 0 if xs is None else 1 + length(xs[1])
def show(xs: IntList) -> str:
parts = []
while xs is not None:
parts.append(str(xs[0]))
xs = xs[1]
return " -> ".join(parts)
xs: IntList = (1, (2, (3, None)))
print("sum:", total(xs))
print("length:", length(xs))
print("list:", show(xs))
print("alias:", IntList.__value__)
sum: 6
length: 3
list: 1 -> 2 -> 3
alias: tuple[int, IntList] | None
- Verdict: native. The
typestatement (Python 3.12 and later) makes an alias that can name itself. Here a list isNoneor a pair of a head and a shorter list. - The value of the alias is evaluated only when the program asks for it, so the name
IntListcan appear in its own definition. - A class can also refer to itself, as the
Treeclass in the idea block does.
#include <iostream>
#include <memory>
struct Node {
int value;
std::unique_ptr<Node> next;
static inline int destroyed = 0;
~Node() { ++destroyed; }
};
std::unique_ptr<Node> cons(int value, std::unique_ptr<Node> next) {
auto n = std::make_unique<Node>();
n->value = value;
n->next = std::move(next);
return n;
}
int total(const Node *n) { return n == nullptr ? 0 : n->value + total(n->next.get()); }
int length(const Node *n) { return n == nullptr ? 0 : 1 + length(n->next.get()); }
int main() {
{
auto xs = cons(1, cons(2, cons(3, nullptr)));
std::cout << "sum: " << total(xs.get()) << '\n';
std::cout << "length: " << length(xs.get()) << '\n';
std::cout << "list:";
for (const Node *n = xs.get(); n != nullptr; n = n->next.get()) {
std::cout << (n == xs.get() ? " " : " -> ") << n->value;
}
std::cout << '\n';
Node::destroyed = 0;
}
std::cout << "destroyed: " << Node::destroyed << '\n';
}
sum: 6
length: 3
list: 1 -> 2 -> 3
destroyed: 3
- Verdict: native.
Nodeholds astd::unique_ptr<Node>, which owns the next node. A field of typeNodeitself would not compile, because the class is incomplete inside its own body. - When the head goes out of scope, each node destroys the next one, so the whole list is freed.
- The destructor of a long list calls itself once for each node, so a very long list can overflow the stack. A loop that releases the nodes one by one avoids this.
sealed interface IntList permits Nil, Cons {}
record Nil() implements IntList {}
record Cons(int head, IntList tail) implements IntList {}
public class Main {
static int total(IntList xs) {
return switch (xs) {
case Nil n -> 0;
case Cons c -> c.head() + total(c.tail());
};
}
static int length(IntList xs) {
return switch (xs) {
case Nil n -> 0;
case Cons c -> 1 + length(c.tail());
};
}
public static void main(String[] args) {
IntList xs = new Cons(1, new Cons(2, new Cons(3, new Nil())));
System.out.println("sum: " + total(xs));
System.out.println("length: " + length(xs));
System.out.println("record: " + xs);
}
}
sum: 6
length: 3
record: Cons[head=1, tail=Cons[head=2, tail=Cons[head=3, tail=Nil[]]]]
- Verdict: native. A field of a class or record type holds a reference, so
Conscan have a field of typeIntList, the interface that it implements. - The sealed interface lists the two cases, so the
switchneeds nodefault. - The generated
toStringof a record callstoStringon each field, so it shows the whole list.
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node *next;
};
static struct node *cons(int value, struct node *next) {
struct node *n = malloc(sizeof *n);
if (n == NULL) {
exit(1);
}
n->value = value;
n->next = next;
return n;
}
static int total(const struct node *n) {
return n == NULL ? 0 : n->value + total(n->next);
}
static int length(const struct node *n) {
return n == NULL ? 0 : 1 + length(n->next);
}
static int release(struct node *n) {
int count = 0;
while (n != NULL) {
struct node *next = n->next;
free(n);
n = next;
count++;
}
return count;
}
int main(void) {
struct node *xs = cons(1, cons(2, cons(3, NULL)));
printf("sum: %d\n", total(xs));
printf("length: %d\n", length(xs));
printf("list:");
for (const struct node *n = xs; n != NULL; n = n->next) {
printf(n == xs ? " %d" : " -> %d", n->value);
}
printf("\n");
printf("freed: %d\n", release(xs));
return 0;
}
sum: 6
length: 3
list: 1 -> 2 -> 3
freed: 3
- Verdict: native. The struct holds a pointer to its own struct type. The tag
struct nodeis in scope inside its own body, so the fieldnextcan name it. - A field of type
struct node(with no*) does not compile, because the type is not complete there. - The program must free each node.
releaseuses a loop, so it also works for long lists.
using System;
static int Total(IntList xs) => xs switch
{
Cons c => c.Head + Total(c.Tail),
_ => 0,
};
static int Length(IntList xs) => xs switch
{
Cons c => 1 + Length(c.Tail),
_ => 0,
};
IntList xs = new Cons(1, new Cons(2, new Cons(3, new Nil())));
Console.WriteLine($"sum: {Total(xs)}");
Console.WriteLine($"length: {Length(xs)}");
Console.WriteLine($"record: {xs}");
abstract record IntList;
sealed record Nil : IntList;
sealed record Cons(int Head, IntList Tail) : IntList;
sum: 6
length: 3
record: Cons { Head = 1, Tail = Cons { Head = 2, Tail = Cons { Head = 3, Tail = Nil { } } } }
- Verdict: native. A record class holds references, so
Conscan have a field of the base typeIntList. - The generated
ToStringof a record prints each property, so it shows the nested list.
const cons = (head, tail) => ({ head, tail });
function total(xs) {
return xs === null ? 0 : xs.head + total(xs.tail);
}
function length(xs) {
return xs === null ? 0 : 1 + length(xs.tail);
}
function show(xs) {
const parts = [];
for (let n = xs; n !== null; n = n.tail) parts.push(n.head);
return parts.join(" -> ");
}
const xs = cons(1, cons(2, cons(3, null)));
console.log("sum:", total(xs));
console.log("length:", length(xs));
console.log("list:", show(xs));
console.log("json:", JSON.stringify(xs));
sum: 6
length: 3
list: 1 -> 2 -> 3
json: {"head":1,"tail":{"head":2,"tail":{"head":3,"tail":null}}}
- Verdict: idiom. JavaScript has no type declarations, so any object property can hold another object of the same shape.
nullmarks the end of the list. JSON.stringifywalks the nested objects, so the output shows the recursive shape.
type IntList = { head: number; tail: IntList } | null;
type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
function total(xs: IntList): number {
return xs === null ? 0 : xs.head + total(xs.tail);
}
function length(xs: IntList): number {
return xs === null ? 0 : 1 + length(xs.tail);
}
function show(xs: IntList): string {
const parts: number[] = [];
for (let n = xs; n !== null; n = n.tail) parts.push(n.head);
return parts.join(" -> ");
}
function depth(j: Json): number {
if (Array.isArray(j)) return 1 + Math.max(0, ...j.map(depth));
if (j !== null && typeof j === "object") return 1 + Math.max(0, ...Object.values(j).map(depth));
return 0;
}
const xs: IntList = { head: 1, tail: { head: 2, tail: { head: 3, tail: null } } };
console.log("sum:", total(xs));
console.log("length:", length(xs));
console.log("list:", show(xs));
const doc: Json = { name: "tree", children: [{ name: "leaf", children: [] }] };
console.log("json depth:", depth(doc));
sum: 6
length: 3
list: 1 -> 2 -> 3
json depth: 4
- Verdict: native. A type alias can refer to itself inside an object type, an array type or a union.
IntListis an object with a tail of typeIntList, ornull. Jsondescribes any JSON value: an array ofJson, or an object whose values areJson.depthfollows the shape of theJsontype: one call for each array or object.
package main
import (
"fmt"
"strings"
)
type Node struct {
Value int
Next *Node
}
func total(n *Node) int {
if n == nil {
return 0
}
return n.Value + total(n.Next)
}
func length(n *Node) int {
if n == nil {
return 0
}
return 1 + length(n.Next)
}
func show(n *Node) string {
var parts []string
for ; n != nil; n = n.Next {
parts = append(parts, fmt.Sprint(n.Value))
}
return strings.Join(parts, " -> ")
}
func main() {
xs := &Node{1, &Node{2, &Node{3, nil}}}
fmt.Println("sum:", total(xs))
fmt.Println("length:", length(xs))
fmt.Println("list:", show(xs))
var empty *Node
fmt.Println("empty length:", length(empty))
}
sum: 6
length: 3
list: 1 -> 2 -> 3
empty length: 0
- Verdict: native. A struct cannot contain a field of its own type, but it can contain a pointer to it. A
nilpointer is the empty list. - A field
Next Node(with no*) does not compile, because the struct would contain itself.
use std::mem::size_of;
enum List {
Cons(i32, Box<List>),
Nil,
}
use List::{Cons, Nil};
fn total(xs: &List) -> i32 {
match xs {
Cons(head, tail) => head + total(tail),
Nil => 0,
}
}
fn length(xs: &List) -> usize {
match xs {
Cons(_, tail) => 1 + length(tail),
Nil => 0,
}
}
fn show(xs: &List) -> String {
let mut parts = Vec::new();
let mut node = xs;
while let Cons(head, tail) = node {
parts.push(head.to_string());
node = &**tail;
}
parts.join(" -> ")
}
fn main() {
let xs = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
println!("sum: {}", total(&xs));
println!("length: {}", length(&xs));
println!("list: {}", show(&xs));
let same = size_of::<Box<List>>() == size_of::<usize>();
println!("a box is one pointer: {}", if same { "yes" } else { "no" });
}
sum: 6
length: 3
list: 1 -> 2 -> 3
a box is one pointer: yes
- Verdict: native. The
Consvariant holds aBox<List>, a pointer to aListon the heap. Without the box, the compiler reports that the type has infinite size. - A
Boxhas the size of one pointer, so the compiler knows the size ofList. Rc<List>in place ofBox<List>lets two lists share a tail.
Variations and related ideas
- Mutually recursive types. Two or more types that refer to each other, such as a tree and a forest.1
- Generic recursive types. A list of any element type, such as
List<T>. See Generics. - Recursive types with cycles. References can make a structure point back to itself, as in a doubly linked list or a graph. The type is the same, but a walk must remember the nodes that it has seen.
- Infinite structures. With lazy evaluation, a recursive value can be infinite, such as the list of all natural numbers. See Lazy and strict evaluation.
- Folds. A function that replaces each constructor of a recursive type with a function, such as
sumon a list. See fold.
Pitfalls
A recursive type without indirection
In Rust, enum List { Cons(i32, List), Nil } does not compile. The compiler reports "recursive type List has infinite size" and suggests "insert some indirection (e.g., a Box, Rc, or &) to break the cycle".2 C and Go reject the same definition. Put the recursive field behind a pointer, a box or a reference.
Deep data overflows the stack
A recursive function on a recursive type uses one stack frame for each level. A list of a hundred thousand nodes is a hundred thousand levels deep. Python stops such a call at its recursion limit.
This code runs but gives a wrong answer on purpose.
from dataclasses import dataclass
@dataclass
class Node:
value: int
next: "Node | None"
def length(node: Node | None) -> int:
return 0 if node is None else 1 + length(node.next)
head = None
for i in range(100_000):
head = Node(i, head)
try:
print(length(head))
except RecursionError:
print("RecursionError")
RecursionError
The fix is a loop for long, thin structures such as lists: while node is not None: count += 1; node = node.next. In languages without such a limit, the same code can crash the process. Trees that stay balanced are less of a risk, because their depth grows with the logarithm of their size.
A cycle makes a walk run forever
When nodes refer to each other through mutable references, the data can contain a cycle. A function that follows the references until it reaches a base case then never stops. Code that can meet shared or cyclic data must keep a set of the nodes that it has visited.
Cost
Each recursive field is a pointer, so each node costs at least one pointer per recursive field plus the allocation overhead of a separate object. The nodes are spread over the heap, so a walk has worse cache behavior than a loop over an array. A recursive walk uses stack space in proportion to the depth of the data.
History
The C standard shows a self-referential structure, struct tnode, as an example.3 Standard ML and Haskell define recursive data types with constructors, as in the mutually recursive tree and forest types that Wikipedia shows for both languages.18 Later languages added more direct forms: indirect enum cases in Swift, recursive type aliases in TypeScript 3.7, and the type statement in Python 3.12.567
References
- Recursive data type, Wikipedia, the introduction; Theory; Isorecursive types; Equirecursive types
- The Rust Programming Language, 15.1 Using Box<T> to Point to Data on the Heap, Enabling Recursive Types with Boxes
- ISO/IEC 9899:201x, committee draft N1570 (C11), 6.7.2.3 Tags, EXAMPLE 1
- The Go Programming Language Specification, Struct types
- The Swift Programming Language, Enumerations, Recursive Enumerations
- TypeScript 3.7 release notes, More Recursive Type Aliases
- The Python Standard Library, typing, Type aliases
- Haskell 2010 Language Report, Chapter 4 Declarations and Bindings, 4.2.1 Algebraic Datatype Declarations
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag S5GV9J Edit this page History Report an error Markdown