common-lisp Conditional expressions


Example

Conditional expressions can be done with ~[ and ~]. The clauses of the expression are separated using ~;.

By default, ~[ takes an integer from the argument list, and picks the corresponding clause. The clauses start at zero.

(format t "~@{~[First clause~;Second clause~;Third clause~;Fourth clause~]~%~}"
        0 1 2 3)
; First clause
; Second clause
; Third clause
; Fourth clause

The last clause can be separated with ~:; instead to make it the else-clause.

(format t "~@{~[First clause~;Second clause~;Third clause~:;Too high!~]~%~}"
        0 1 2 3 4 5)
; First clause
; Second clause
; Third clause
; Too high!
; Too high!
; Too high!

If the conditional expression starts with ~:[, it will expect a generalized boolean instead of an integer. It can only have two clauses; the first one is printed if the boolean was NIL, and the second clause if it was truthy.

(format t "~@{~:[False!~;True!~]~%~}"
        t nil 10 "Foo" '())
; True!
; False!
; True!
; True!
; False!

If the conditional expression starts with ~@[, there should only be one clause, which is printed if the input, a generalized boolean, was truthy. The boolean will not be consumed if it is truthy.

(format t "~@{~@[~s is truthy!~%~]~}"
        t nil 10 "Foo" '())
; T is truthy!
; 10 is truthy!
; "Foo" is truthy!