Plain recursion uses the call stack. If you recursively call yourself for each element of a large collection, you can blow the stack.
Clojure provides recur as an explicit, safe way to express tail recursion. When you use recur in the correct position, it compiles to a loop without growing the call stack.
The rules you need to remember
recur can only appear in tail position (the final action).
recur can target the nearest loop or the current function.
- If the compiler accepts it, it is stack-safe.
Java mental model: recur is the closest equivalent to a while loop, but expressed in a functional style with explicit state variables.
In this section
-
Tail Recursion in Clojure: A Deep Dive for Java Developers
Explore the concept of tail recursion in Clojure, understand its benefits, and learn how to implement it effectively using the recur keyword. Tail recursion optimizes recursive functions to prevent stack overflow, making it a powerful tool for Java developers transitioning to Clojure.
-
Mastering Recursion with `recur` in Clojure: A Guide for Java Developers
Explore how the `recur` keyword in Clojure optimizes recursive calls by reusing the current stack frame, enabling efficient tail recursion. Learn to rewrite recursive functions using `recur` with examples and comparisons to Java.
-
Understanding the Limitations of `recur` in Clojure
Explore the limitations of the `recur` keyword in Clojure, focusing on its requirement to be in the tail position and its ability to recur only to the nearest enclosing function or loop. Learn how to refactor code to meet these requirements effectively.