Exit in Lisp
Here’s an idiomatic Lisp example demonstrating the concept of exiting a program:
(defun main ()
  ;; This will not be executed due to the exit
  (unwind-protect
       (progn
         (format t "Exiting the program~%")
         (sb-ext:exit :code 3))
    (format t "This cleanup code won't run!~%")))
;; Run the main function
(main)This Lisp program demonstrates how to exit a program with a specific status code. Let’s break it down:
We define a
mainfunction to encapsulate our program logic.Inside
main, we useunwind-protect, which is similar totry-finallyin other languages. It ensures that cleanup code is executed even if an unwind (like an exit) occurs.The
prognform groups multiple expressions together.We use
formatto print a message to the console before exiting.sb-ext:exitis used to exit the program with a specific status code. This is implementation-specific (for SBCL), as Common Lisp doesn’t have a standard way to exit with a status code.The cleanup code inside
unwind-protectwon’t be executed due to the immediate exit.Finally, we call the
mainfunction to run our program.
To run this program:
- Save the code in a file, e.g., 
exit-example.lisp. - Run it using a Common Lisp implementation. For example, with SBCL:
 
$ sbcl --script exit-example.lisp
Exiting the programTo check the exit status in a shell:
$ sbcl --script exit-example.lisp
Exiting the program
$ echo $?
3Note that the cleanup message “This cleanup code won’t run!” is never printed due to the immediate exit.
This example demonstrates how to exit a Lisp program with a specific status code, which is useful for indicating success or failure to the calling process. It also shows that cleanup code in unwind-protect is not executed when using an exit function, which is an important consideration when designing robust Lisp programs.