Condition Testing

cond was the original way to test conditions in Lisp. It is still useful when multiple conditions are to be tested.

(cond ( test_1 ... result_1 )
( test_2 ... result_2 )
...
( else ... result_n ) )

When cond is evaluated, test_1 is evaluated first; if its value is true (anything other than #f), then the remainder of the first clause through result_1 is evaluated, and the value of result_1 is the value of the cond. Otherwise, test_2 is evaluated, and so on. The keyword else may be used as the test of the last clause; its value is always taken as true. Other dialects of Lisp use t instead of else. If no test is true, the value of the cond is undefined.


   (define (abs x)
     (cond ((< x 0) (- x))
           (else x)))

It is good practice for the last test in a cond to be else to guarantee that all cases are covered.

Contents    Page-10    Prev    Next    Page+10    Index