Question

Today i am reading the book "A Gentle Introduction to Symbolic Computation", and i got to the exercise 4.29. Here how it sounds like: "Write versions of LOGICAL-AND using IF and COND instead of AND."

Here how it was defined in the original text:

(defun logical-and (x y) (and x y t))

That is how i defined it with cond and if:

(defun logical-and (x y)
  (cond ((and x y) t) 
    (t nil)))

(defun logical-and (x y) 
  (if (and x y) t nil))

And that is how they are defined in the answers to the exercises

(defun logical-and (x y)
  (cond (x (cond (y t)))))

(defun logical-and (x y)
  (if x (if y t)))

So the question is are all these definitions equal?

Was it helpful?

Solution

All three cases are identitical in behaviour. Specifically the function returns the symbol t if x and y are both non-nil, and nil otherwise.

In the definition in the text, it simply uses the and operator with t as it's last argument. This works because if either x or y are nil then, and short circuits and returns nil, however if both x and y are true, then and returns the result of the last expressions, which is t.

In your cond definition, if both x and y are true, the first clause matches, returning t, and in all other cases (i.e. either x or y is false) nil is returned.

Your if definition works similarly, returning t if and only if both x and y are true, and nil otherwise.

The answers to the exercise work because cond returns nil if no clause matches and if returns nil if the conditional is false and no else clause is specified. Therefore the cond definition returns t only if both conditions are satisfied (i.e. x is true and y is true), and the if defintion is t only if both if conditions are true, and if not nil is returned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top