Trampoline
Tutorial Video
Text description (accessibility)
This video demonstrates the "Trampoline" functional Rust example. Difficulty level: Advanced. Key concepts covered: Functional Programming. Rust (and OCaml without tail-call optimization) stack-overflows on deeply recursive functions. Key difference from OCaml: 1. **TCO guarantee**: OCaml guarantees TCO for direct tail calls; Rust does not — trampolining is always required for stack
Tutorial
The Problem
Rust (and OCaml without tail-call optimization) stack-overflows on deeply recursive functions. A trampoline converts stack recursion into heap iteration: instead of calling the next step recursively, return a thunk (a suspended computation). The trampoline loop executes thunks iteratively on the heap, never growing the call stack. This enables "infinite" recursion and mutual recursion on arbitrary inputs without stack overflow.
🎯 Learning Outcomes
Done(value) or More(thunk) instead of recursingCode Example
#![allow(clippy::all)]
// Stub — awaiting conversion from OCaml source.Key Differences
Box<dyn FnOnce>; OCaml's TCO reuses the stack frame — zero allocation.OCaml Approach
OCaml guarantees tail call optimization for direct tail calls:
let rec factorial n acc = if n = 0 then acc else factorial (n-1) (n*acc)
This is already stack-safe in OCaml. Trampolining is only needed in OCaml for mutually recursive functions that the compiler cannot prove are tail-recursive. OCaml's tailcall ppx annotation forces TCO and warns if it fails.
Full Source
#![allow(clippy::all)]
// Stub — awaiting conversion from OCaml source.Deep Comparison
OCaml vs Rust: Trampoline
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.
Exercises
is_even(n) and is_odd(n) using Trampoline with no stack growth.trampoline! that transforms a recursive function into its trampolined equivalent automatically.