Recursive data and recursive code. We’ll use a phylogenetic tree as the example throughout — first the data type, then the functions that walk it.
A tree is a type that contains itself: a node holds its children, which are nodes
Rust needs one extra ingredient — a small trick to give the compiler a fixed size — to make that type compile
Once we have the type, the functions almost write themselves
A real lineage tree — great apes
Before any code, here is the kind of object we are going to model — a real, small phylogeny:
A great-apes phylogeny: Human and Chimpanzee share an ancestor ~6 million years ago; Gorilla joins higher up at ~9 MYA. Branch lengths are proportional to time.
The shape is what we want to capture in Rust: two tips share a recent common ancestor; a third tip joins higher up. Throughout the lecture we’ll use the same shape with abstract names (A, B, C) so the code stays compact — but the structure is the same as Human / Chimp / Gorilla above.
Phylogenetic trees — what we want to model
A phylogeny (a branching diagram of evolutionary relationships) is built from internal nodes (inferred common ancestors) and tips / leaves (present-day samples).
At each node we record a name (at tips) and a branch length — the evolutionary distance to the parent.
Same tree as a picture, a Newick string, and a Rust enum literal.
Why this won’t compile yet
// This does NOT compile:enum Node { Internal { left: Node, right: Node }, Leaf,}// error[E0072]: recursive type `Node` has infinite size
The 1 is the variant tag; the 2 × size(Node) is two child Nodes inlined into the parent — that’s the part with no finite answer.
The fix: store a pointer to each child instead of the child itself.
Box<T> — indirection makes it work
Box<T> = a small handle (8 bytes) that points to a value stored elsewhere in memory (“the heap” [the region the program allocates from at runtime when sizes aren’t known up front]).
The parent’s size is now fixed; the child lives somewhere else.
Box turns infinite recursion into a fixed-size pointer.
A leaf is a tip species; an internal node groups child sub-trees. Vec<Node> provides the indirection (heap-allocated children) and the variable arity (two children or twenty — same type).
Building a tree by hand
The cleanest way to test a tree function: hard-code a small tree in main and call your function on it.
fn main() {// The tree ((A:0.1, B:0.2):0.3, C:0.5);let tree =Node::Internal { branch_length:0.0, children:vec![Node::Internal { branch_length:0.3, children:vec![Node::Leaf { name:"A".to_string(), branch_length:0.1},Node::Leaf { name:"B".to_string(), branch_length:0.2}, ],},Node::Leaf { name:"C".to_string(), branch_length:0.5}, ],};println!("{} tips", count_tips(&tree));}
The repetition is on purpose: when you can read the structure of the literal, you can read any recursive enum.
A two-tip warm-up — the simplest tree
Before counting tips of the 3-tip tree, here’s the absolute minimum:
Two leaves under one ancestor. If count_tips(&tiny) returns 2, your function works on the base cases (leaves) and on a one-deep recursive case. The 3-tip tree on the next slide adds a second level.
Recursive functions — match the type
To count the tips of a tree:
if the tree is a Leaf, the answer is 1. If Internal, the answer is the sum of the tip counts of each child.
The explicit shape — an accumulator and a loop:
fn count_tips(node:&Node) ->usize{match node {Node::Leaf {..}=>1,Node::Internal { children,..}=>{letmut total =0;for child in children { total += count_tips(child);} total}}}
The idiomatic Rust version
The idiomatic Rust version collapses the loop into an iterator chain:
Same code, same speed — the second is what you’ll see in Rust idiom.
Counting tips — step by step
Count accumulates bottom-up — leaves return 1, each internal node sums its children.
Step 1: the example tree with no annotations.
Step 2: each leaf returns 1.
Step 3: internal node (A,B) sums its children — 1 + 1 = 2.
Step 4: root sums its children — 2 + 1 = 3.
Another walk: deepest leaf
The depth of a tree is the longest path from the root to any leaf. A leaf is at depth 0. An internal node is at depth 1 + the max depth among its children.
Same shape as count_tips: one arm per variant, recursive call per child, combine with an iterator method.
About the unwrap_or(0): .max() on an empty list returns None (no answer); unwrap_or(0) says “treat that as 0”. An internal node with no children is biologically odd but allowed by the type — this keeps the function total.
Max depth — step by step
Same bottom-up flow as tip-counting, but the combiner is max over branch-lengths instead of sum.
Step 1: the tree without depth annotations.
Step 2: each leaf returns its own branch length (0.1, 0.2, 0.5).
For ((A:0.1, B:0.2):0.3, C:0.5); this returns ["A", "B", "C"].
flat_map (a built-in iterator method that maps and flattens in one step) collects each child’s Vec of names and chains them together — the recursive pattern is identical to count_tips, but the return type changed.
More walks of the same shape
Once you have the recursion pattern, biology walks pour out:
Function
Returns
Combine
total_branch_length(node)
f64
sum of own + all children’s
count_internal_nodes(node)
usize
1 + sum of children’s (Leaf returns 0)
find_tip(node, name)
Option<...>
first matching leaf, else recurse
tips_at_depth(node, d)
Vec<String>
tips whose root-distance equals d
prune_by_name(node, names)
Option<Node>
drop subtrees whose only tips are in names
All the same shape: match Leaf vs Internal, base case + recursive case, combine the children’s answers. The combinator changes (+, max, concat, first match, etc.) but the skeleton is identical.
Recursion has a depth cost
Every recursive call pushes a stack frame onto the call stack.
max_depth(root)
max_depth(child_1)
max_depth(grandchild_1a)
max_depth(great_grandchild_1a_i) ← deeper = more frames
...
The stack has a fixed size (a few megabytes by default). Very deep recursion can run out of room — a stack overflow.
When recursion is safe
When recursion depth matters:
Phylogenies: a few hundred internal nodes at most — well within the budget. Recursion is fine.
Long sequences: a million bases would mean a million frames — would crash. Use an explicit loop or an iterative work-list instead.
Rust does not guarantee tail-call optimisation; some other languages do, but you can’t rely on it here.
To the next lecture
Next lecture: when recursion isn’t enough — dynamic programming, with sequence alignment as the example.