Next: , Previous: if, Up: Writing Defuns

3.8 If–then–else Expressions

An if expression may have an optional third argument, called the else-part, for the case when the true-or-false-test returns false. When this happens, the second argument or then-part of the overall if expression is not evaluated, but the third or else-part is evaluated. You might think of this as the cloudy day alternative for the decision “if it is warm and sunny, then go to the beach, else read a book!”.

The word “else” is not written in the Lisp code; the else-part of an if expression comes after the then-part. In the written Lisp, the else-part is usually written to start on a line of its own and is indented less than the then-part:

     (if true-or-false-test
         action-to-carry-out-if-the-test-returns-true
       action-to-carry-out-if-the-test-returns-false)

For example, the following if expression prints the message ‘4 is not greater than 5!’ when you evaluate it in the usual way:

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

Note that the different levels of indentation make it easy to distinguish the then-part from the else-part. (GNU Emacs has several commands that automatically indent if expressions correctly. See GNU Emacs Helps You Type Lists.)

We can extend the type-of-animal function to include an else-part by simply incorporating an additional part to the if expression.

You can see the consequences of doing this if you evaluate the following version of the type-of-animal function definition to install it and then evaluate the two subsequent expressions to pass different arguments to the function.

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

     (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!"; but when you evaluate (type-of-animal 'zebra), you will see "It's not fierce!".

(Of course, if the characteristic were ferocious, the message "It's not fierce!" would be printed; and it would be misleading! When you write code, you need to take into account the possibility that some such argument will be tested by the if and write your program accordingly.)