Next: , Up: if

if in more detail

An if expression written in Lisp does not use the word `then'; the test and the action are the second and third elements of the list whose first element is if. Nonetheless, the test part of an if expression is often called the if-part and the second argument is often called the then-part.

Also, when an if expression is written, the true-or-false-test is usually written on the same line as the symbol if, but the action to carry out if the test is true, the “then-part”, is written on the second and subsequent lines. This makes the if expression easier to read.

     (if true-or-false-test

The true-or-false-test will be an expression that is evaluated by the Lisp interpreter.

Here is an example that you can evaluate in the usual manner. The test is whether the number 5 is greater than the number 4. Since it is, the message ‘5 is greater than 4!’ will be printed.

     (if (> 5 4)                             ; if-part
         (message "5 is greater than 4!"))   ; then-part

(The function > tests whether its first argument is greater than its second argument and returns true if it is.) Of course, in actual use, the test in an if expression will not be fixed for all time as it is by the expression (> 5 4). Instead, at least one of the variables used in the test will be bound to a value that is not known ahead of time. (If the value were known ahead of time, we would not need to run the test!)

For example, the value may be bound to an argument of a function definition. In the following function definition, the character of the animal is a value that is passed to the function. If the value bound to characteristic is fierce, then the message, ‘It's a tiger!’ will be printed; otherwise, nil will be returned.

     (defun type-of-animal (characteristic)
       "Print message in echo area depending on CHARACTERISTIC.
     If the CHARACTERISTIC is the symbol `fierce',
     then warn of a tiger."
       (if (equal characteristic 'fierce)
           (message "It's a tiger!")))

If you are reading this inside of GNU Emacs, you can evaluate the function definition in the usual way to install it in Emacs, and then you can evaluate the following two expressions to see the results:

     (type-of-animal 'fierce)
     (type-of-animal 'zebra)

When you evaluate (type-of-animal 'fierce), you will see the following message printed in the echo area: "It's a tiger!"; and when you evaluate (type-of-animal 'zebra) you will see nil printed in the echo area.