Recursion in Lisp
Our example demonstrates recursive functions in Lisp. Here’s a classic example.
This fact
function calls itself until it reaches the base case of (fact 0)
.
In Lisp, we don’t need to explicitly declare recursive closures before defining them, as we do in some other languages. Lisp’s lexical scoping allows us to define recursive local functions easily.
The fib
function is defined as a local function using lambda
. It can refer to itself directly within its own body.
To run this program, save it to a file (e.g., recursion.lisp
) and run it with your Lisp interpreter. For example, if you’re using SBCL:
This output shows the factorial of 7 (5040) and the 7th Fibonacci number (13).
Lisp’s support for recursion and closures makes it easy to write elegant recursive functions, both as top-level definitions and as local functions.