Switch in Lisp

Switch statements express conditionals across many branches.

Here’s a basic switch.

(let ((i 2))
  (format t "Write ~d as " i)
  (case i
    (1 (format t "one~%"))
    (2 (format t "two~%"))
    (3 (format t "three~%"))))

You can use commas to separate multiple expressions in the same case statement. We use the optional default case in this example as well.

(case (nth-value 6 (get-universal-time))
  ((6 0) (format t "It's the weekend~%"))
  (otherwise (format t "It's a weekday~%")))

switch without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants.

(let ((hour (nth-value 3 (get-universal-time))))
  (cond
    ((< hour 12) (format t "It's before noon~%"))
    (t (format t "It's after noon~%"))))

A type switch compares types instead of values. You can use this to discover the type of a value. In this example, the variable t will have the type corresponding to its clause.

(defun what-am-i (i)
  (cond
    ((typep i 'boolean) (format t "I'm a bool~%"))
    ((typep i 'integer) (format t "I'm an int~%"))
    (t (format t "Don't know type ~a~%" (type-of i)))))

(what-am-i t)
(what-am-i 1)
(what-am-i "hey")
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type (SIMPLE-BASE-STRING 3)