liveBook · Manning

Mutual recursion

As explained in Clojure: The Essential Reference

Mutual recursion is a recursive computation in which two or more functions call one another.

Mutual recursion is a computation in which two or more functions call one another. In Clojure, letfn makes the functions visible throughout the local binding chain, allowing forward and backward references. This supports self-contained recursive logic without moving private helper functions outside their enclosing function. section 3.1.3

Direct mutual recursion consumes a stack frame for each transition. Return the next call as a function, then use trampoline to invoke returned functions repeatedly until a non-function result appears. This converts the recursive sequence into tail-recursive iteration and avoids stack overflow for long runs. The function must eventually return a non-function value; otherwise trampoline recurses indefinitely. section 2.4.3

Alternating parity checks

letfn defines is-even? and is-odd? together. Each function returns a deferred call to the other, and trampoline drives the sequence: (trampoline is-odd? 120) returns false. The same pattern can model state machines, such as traffic-light transitions, where millions of transitions complete without consuming one stack frame per state. section 2.4.3

How Clojure: The Essential Reference covers it

How deep it goes
Explains local binding visibility, deferred calls, trampoline's type-based exit condition, and the infinite-recursion failure case.
Examples
Demonstrates alternating parity predicates and a traffic-light state machine with short and very long transition sequences.
What it assumes
Assumes familiarity with Clojure functions and recursion while teaching local recursive bindings and trampoline's deferred-call protocol.
What you can do after
Apply it via Clojure's letfn and trampoline to build stack-safe alternating computations and state transitions.
How it connects
Connects mutual recursion to letfn, trampoline, tail recursion, state machines, lexical binding, and stack overflow.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.