Clojure Recursion — loop and recur, Stack-Safe | Episode 16

0views
C
CelesteAI
Description
Clojure's `recur` is the tail-call jump that makes recursion stack-safe. Paired with `loop`, you get a local recursion point with named bindings — perfect for counters, accumulators, and any walk that needs custom flow. In this episode we build factorial with `loop`/`recur`, prove it works on huge inputs with `20N`, write `sum-to-n` in the same shape, and walk a nested tree of branches and leaves using an explicit stack. Along the way, we call out when to reach for map, filter, and reduce instead. Phase 3 continues! Student code: https://github.com/GoCelesteAI/clojure-for-beginners/tree/main/episode16 Every keystroke is shown on screen with generous pauses so you can follow along at your own pace. What You'll Learn: - loop — a local recursion point with named bindings - recur — tail-call jump that reuses the stack frame - Factorial and sum-to-n — the classic counter plus accumulator pattern - Tree walker — an explicit stack pushed through loop/recur - When to use map, filter, and reduce instead of hand-rolled recursion Timestamps: 0:00 - Intro 0:12 - Preview: loop, recur, stack safety 0:32 - Start the REPL 0:40 - loop and recur basics 1:00 - factorial in the REPL 1:30 - Exit REPL 1:35 - Write recursion.clj in Neovim 1:50 - factorial section 4:20 - big factorials with 20N 5:10 - sum-to-n section 7:40 - tree walker with an explicit stack 9:50 - when to reach for HOFs instead 10:20 - Run with :!clj -M % 10:30 - Output walked through 11:20 - Review 11:30 - Recap 12:00 - What's next: Episode 17 Key Takeaways: 1. recur jumps back to the nearest loop or fn without consuming a new stack frame — recursion stays safe for huge inputs. 2. loop sets a local recursion point with named bindings; perfect for index plus accumulator patterns. 3. Factorial and sum-to-n share the same shape — count down or up, carry an accumulator. 4. Tree walkers use an explicit stack pushed and popped through loop/recur. 5. Reach for map, filter, and reduce first — drop to loop/recur only when you need custom flow. Phase 3 continues! Next up, Episode 17 — function composition with comp, partial, and juxt. Taught by CelesteAI. Like and subscribe for more Clojure tutorials!
Back to tutorials

Duration

Added to Codegiz

April 18, 2026

📖 Read the articleOpen in YouTube