next up previous
Contents Next: cons (FUNTION) Up: Appendix: Selected LISP Previous: cdr (Function)

cond (MACRO)

Format: (cond (<test1> <body1>) (<test2> <body2>) . . (<testN> <bodyN>))

Required arguments: none

Optional arguments: zero or more (<test> <body>) clauses

Here, <test> is any LISP expression. The <body> is a sequence of zero or more LISP expressions.

Each <test> expression is evaluated in turn, until one is found whose value is non-NIL. For this clause, the sequence of <body> expressions are evaluated and the value of the last expression is returned as the result of cond. If no successful <test> expression is found, cond returns NIL. If a successful <test> expression is found, but its clause contains no <body> expressions, the result of the <test> expression is returned as the result of cond.

Examples:

> (setq a '3)
3
> (setq b '4)
4

> (cond ((= a b) 'equal)
        ((< a b) 'b-is-bigger)
        (t 'a-is-bigger))
B-IS-BIGGER

> (setq action 'square-both)
SQUARE-BOTH

> (cond ((equal action 'clear-both)
         (setq a 0) 
         (setq b 0))
        ((equal action 'square-both)
         (setq a (* a a))
         (setq b (* b b)))
        ((equal action 'square-a)
         (setq a (* a a)))
        ((equal action 'square-b)
         (setq b (* b b))))
16

> (cond ((= a 5) 'found)
        ((= b 5) 'found))
NIL

> (cond ((+ a 1)))   ; strange use of cond
10                   ; before this, a was 9 due to previous
                     ; cond clauses



© Colin Allen & Maneesh Dhagat
November 1999