If Else in Lisp

(defun main ()
  ;; Here's a basic example.
  (if (= (mod 7 2) 0)
      (format t "7 is even~%")
      (format t "7 is odd~%"))

  ;; You can have an 'if' statement without an else.
  (when (= (mod 8 4) 0)
    (format t "8 is divisible by 4~%"))

  ;; Logical operators like 'and' and 'or' are often useful in conditions.
  (when (or (= (mod 8 2) 0) (= (mod 7 2) 0))
    (format t "either 8 or 7 are even~%"))

  ;; A let binding can precede conditionals; any variables
  ;; declared in this binding are available in the current
  ;; and all subsequent branches.
  (let ((num 9))
    (cond ((< num 0) (format t "~A is negative~%" num))
          ((< num 10) (format t "~A has 1 digit~%" num))
          (t (format t "~A has multiple digits~%" num)))))

(main)

Branching with if and else in Lisp is straightforward. Here’s how the different constructs work:

  1. Basic if-else: In Lisp, if takes three arguments: the condition, the then-clause, and the else-clause.

  2. if without else: In Lisp, we use when for this. It executes the body only if the condition is true.

  3. Logical operators: Lisp uses and and or for logical operations.

  4. Variable declaration before conditional: In Lisp, we use let to create local bindings. The cond macro is then used for multiple conditions.

Note that in Lisp, you don’t need parentheses around conditions, but the entire expression is enclosed in parentheses.

To run this Lisp program:

$ sbcl --script if-else.lisp
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Lisp doesn’t have a ternary operator, but the if special form can be used for simple conditions, and cond for more complex ones.