Recursion in Lisp

Our example demonstrates recursive functions in Lisp. Here’s a classic example.

(defun fact (n)
  (if (= n 0)
      1
      (* n (fact (- n 1)))))

(defun main ()
  (format t "~A~%" (fact 7))

  ;; Closures can also be recursive in Lisp
  (let ((fib 
         (lambda (n)
           (if (< n 2)
               n
               (+ (funcall fib (- n 1))
                  (funcall fib (- n 2)))))))
    (format t "~A~%" (funcall fib 7))))

(main)

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:

$ sbcl --script recursion.lisp
5040
13

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.