Node:Recursion with cond, Next:, Previous:Recursive triangle function, Up:Recursion



11.3.5 Recursion Example Using cond

The version of triangle-recursively described earlier is written with the if special form. It can also be written using another special form called cond. The name of the special form cond is an abbreviation of the word conditional.

Although the cond special form is not used as often in the Emacs Lisp sources as if, it is used often enough to justify explaining it.

The template for a cond expression looks like this:

(cond
 body...)

where the body is a series of lists.

Written out more fully, the template looks like this:

(cond
 (first-true-or-false-test first-consequent)
 (second-true-or-false-test second-consequent)
 (third-true-or-false-test third-consequent)
  ...)

When the Lisp interpreter evaluates the cond expression, it evaluates the first element (the CAR or true-or-false-test) of the first expression in a series of expressions within the body of the cond.

If the true-or-false-test returns nil the rest of that expression, the consequent, is skipped and the true-or-false-test of the next expression is evaluated. When an expression is found whose true-or-false-test returns a value that is not nil, the consequent of that expression is evaluated. The consequent can be one or more expressions. If the consequent consists of more than one expression, the expressions are evaluated in sequence and the value of the last one is returned. If the expression does not have a consequent, the value of the true-or-false-test is returned.

If none of the true-or-false-tests test true, the cond expression returns nil.

Written using cond, the triangle function looks like this:

(defun triangle-using-cond (number)
  (cond ((<= number 0) 0)
        ((= number 1) 1)
        ((> number 1)
         (+ number (triangle-using-cond (1- number))))))

In this example, the cond returns 0 if the number is less than or equal to 0, it returns 1 if the number is 1 and it evaluates (+ number (triangle-using-cond (1- number))) if the number is greater than 1.