Conditional expressions

There are two widely-used forms of conditional expression in Lisp: if and cond.

if

The primitive conditional form in Lisp is the special operator called if. The syntax follows that outlined for function application, so it looks like a call to the function called if. Of course, this is not the case, since the whole purpose of if is to evaluate either the consequent, also known as the then-part, or the alternative, also known as the else-part, but not both.

(if condition consequent alternative)

Each of condition, consequent and alternative can be arbitary Lisp expressions. In some Lisps the alternative is optional, but in EuLisp it is required. It is good practice to include it anyway. Here are the obvious examples with predictable results:

user> (if () "true" "false") "false" user> (if t "true" "false") "true"

cond

A more general form of if provides the chained if-then-elif ... construct of other programming languages. This operator is called cond and looks like this: (cond (exp-11 exp-12) (exp-21 exp-22) ... (exp-n1 exp-n2)) Each of the expressions exp-i1 is evaluated in turn to find one whose result is true. Then exp-i2 is evaluated and the result of this is the result of the cond expression. If none of the exp-i1 results in true, the result of the cond expression is (). Thus, the above cond expression is equivalent to (if exp-11 exp-12 (if exp-21 exp-22 ... (if exp-n1 exp-n2 ()) ... )) Taking the same two examples as used for if above, we get: user> (cond (() "true") (t "false")) "false" user> (cond (t "true") (() "false")) "true" user> Although the behaviour of this chained if expression is no different from any other programming language, it may be worth reiterating that the tests are evaluated in turn so more specific tests should be carried out before more general ones.
Julian Padget, jap@maths.bath.ac.uk, this version December 9, 1994