Lisp Books

Saturday 17 April 2010

Using COND in Common Lisp

Our last post looked at IF THEN statements using the IF function in Lisp. Here's the answer to the challenge set in that post, to write a MY-ABSOLUTE function using an IF function:
(defun my-absolute (x)
              (if (>= x 0) x
                (* -1 x)))

COND
It's possible to use multiple IF functions but if you have lots of things to test it can be more convenient to use a COND function.

COND is a conditional function. It consists of any number of
test and consequent clauses.

(COND (first-test first-consequent)
(second-test second-consequent)
....
(last-test last-consequent))

COND works by progressing through each clause in turn. If the test part is true, COND evaluates the consequent part and returns its value, it does not evaluate any further clauses.

If the test evaluates to NIL (false), COND jumps to the next clause. If all clauses are false, COND returns NIL.
Here's an example COND function:

(defun what-is (x)
  (cond ((equal x ’apple) ’fruit)
    ((equal x ’asparagus) ’vegetable)
    ((equal x ’pork-chop) ’meat)
    (t ’unknown)))

As shown in the example above, it's useful to put a T as the last COND clause. This allows you to return a value or perform another task if all of the preceeding clauses are false.

Today's Challenge:
Write a function called MY-COMPARE using COND that will take two numbers as input and return one of these statements as appropriate:

THE FIRST NUMBER IS LARGER
THE SECOND NUMBER IS LARGER
THE TWO NUMBERS ARE EQUAL