Conditional control structures choose among alternatives. Emacs Lisp
has five conditional forms:
if, which is much the same as in
unless, which are variants of
cond, which is a generalized case statement;
pcase, which is a generalization of
(see Pattern-Matching Conditional).
ifchooses between the then-form and the else-forms based on the value of condition. If the evaluated condition is non-
nil, then-form is evaluated and the result returned. Otherwise, the else-forms are evaluated in textual order, and the value of the last one is returned. (The else part of
ifis an example of an implicit
progn. See Sequencing.)
If condition has the value
nil, and no else-forms are given,
ifis a special form because the branch that is not selected is never evaluated—it is ignored. Thus, in this example,
trueis not printed because(if nil (print 'true) 'very-false) ⇒ very-false
This is a variant of
ifwhere there are no else-forms, and possibly several then-forms. In particular,(when condition a b c)
is entirely equivalent to(if condition (progn a b c) nil)
This is a variant of
ifwhere there is no then-form:(unless condition a b c)
is entirely equivalent to(if condition nil a b c)
condchooses among an arbitrary number of alternatives. Each clause in the
condmust be a list. The car of this list is the condition; the remaining elements, if any, the body-forms. Thus, a clause looks like this:(condition body-forms...)
condtries the clauses in textual order, by evaluating the condition of each clause. If the value of condition is non-
nil, the clause succeeds; then
condevaluates its body-forms, and returns the value of the last of body-forms. Any remaining clauses are ignored.
If the value of condition is
nil, the clause fails, so the
condmoves on to the following clause, trying its condition.
A clause may also look like this:(condition)
Then, if condition is non-
nilwhen tested, the
condform returns the value of condition.
If every condition evaluates to
nil, so that every clause fails,
The following example has four clauses, which test for the cases where the value of
xis a number, string, buffer and symbol, respectively:(cond ((numberp x) x) ((stringp x) x) ((bufferp x) (setq temporary-hack x) ; multiple body-forms (buffer-name x)) ; in one clause ((symbolp x) (symbol-value x)))
Often we want to execute the last clause whenever none of the previous clauses was successful. To do this, we use
tas the condition of the last clause, like this:
). The form
t, which is never
nil, so this clause never fails, provided the
condgets to it at all. For example:(setq a 5) (cond ((eq a 'hack) 'foo) (t "default")) ⇒ "default"
fooif the value of
hack, and returns the string
Any conditional construct can be expressed with
cond or with
if. Therefore, the choice between them is a matter of style.
(if a b c) == (cond (a b) (t c))