Factorial in Lisp

Example for versions Corman Common Lisp 3.0, SBCL 1.0.1, SBCL 1.0.29, clisp 2.47, gcl 2.6.6

This example uses recursive factorial definition (which is natural for Lisp). Features:

  • math operators: (- n 1) is prefix notation equivalent to n-1 in infix notation;
  • comparison operators: (= n 0) evaluates to T if n is zero, and to nil (used as false) otherwise;
  • conditional operator if: Lisp expressions are evaluated using brackets, so they can be written in several lines;
  • function definition using defun;
  • Common Lisp macro loop;
  • format specifiers in format: ~D corresponds to printing an integer, and ~% is end-of-line.
(defun factorial (n)
  (if (= n 0)
      1
      (* n (factorial (- n 1))) ) )

(loop for i from 0 to 16
   do (format t "~D! = ~D~%" i (factorial i)) )