COND

Another time raw **IF** expressions can get ugly is when you have a multibranch conditional: if a do x, else if b do y; else do z. There’s no logical problem writing such a chain of conditional expressions with just **IF**, but it’s not pretty.

  1. (if a
  2. (do-x)
  3. (if b
  4. (do-y)
  5. (do-z)))

And it would be even worse if you needed to include multiple forms in the then clauses, requiring **PROGN**s. So, not surprisingly, Common Lisp provides a macro for expressing multibranch conditionals: **COND**. This is the basic skeleton:

  1. (cond
  2. (test-1 form*)
  3. .
  4. .
  5. .
  6. (test-N form*))

Each element of the body represents one branch of the conditional and consists of a list containing a condition form and zero or more forms to be evaluated if that branch is chosen. The conditions are evaluated in the order the branches appear in the body until one of them evaluates to true. At that point, the remaining forms in that branch are evaluated, and the value of the last form in the branch is returned as the value of the **COND** as a whole. If the branch contains no forms after the condition, the value of the condition is returned instead. By convention, the branch representing the final else clause in an if/else-if chain is written with a condition of **T**. Any non-**NIL** value will work, but a **T** serves as a useful landmark when reading the code. Thus, you can write the previous nested **IF** expression using **COND** like this:

  1. (cond (a (do-x))
  2. (b (do-y))
  3. (t (do-z)))