next up previous
Contents Next: Recursion and Iteration Up: Defining Lisp functions Previous: Logical Operators: And


Use the Lisp interpreter to help you learn or refresh your memory about the behavior of these predicates: > , <, > =, <=, =, zerop, numberp, symbolp, atom, constantp, listp, functionp

Consider the following definition:
(defun life (a b)
  (cond ((null a) b)
        ((null b) a)
        (t 'its-tough)))
Suppose you are running the Lisp interpreter and you enter the following:
> (setf a 'oh-boy)
Then you do the following:
> (life 'gummi a)
What are the global and local values of a and b before, during, and after this command?

Consider the following function definition:
(defun who-knows (lst1 lst2)
  (cond ((= (length lst1) (length lst2))
         (+ (length lst1) (length lst2)))
        ((>  (length lst1) (length lst2))  (length lst2))
        (t   (length lst1))))
What does this function do? Be precise as what would happen in each case.
How would you make this function crash (return an ERROR)? Be careful in explaining why it will happen.

Write a function called BLENGTH (B stands for better) which is more tolerant of bad arguments, and is more informative. It works as follows:
> (blength '(a b c d))

> (blength 'hello)
(sorry hello is an atom)

> (blength 4)
(sorry 4 is a number)
Thus, if a list is passed in it should return the proper length, else if a number, or another type of atom is passed in, it should identify them as such.

Consider the following definition for the function CIRCULATE:
(defun circulate (lst)
  (append (rest lst)
          (list (first lst))))
This function takes a list and constructs a new list by taking the first element of the old list and making it the last element of the new. For example:
> (circulate '((whats) happening here))
(happening here (whats))
Rewrite the function and call it CIRCULATE-DIR so that it can circulate lists in both directions. Thus it should work as follows:
> (circulate-dir '(1 2 3 4) 'left)
(4 1 2 3)

> (circulate-dir '(1 2 3 4) 'right)
(2 3 4 1)

With the definition of CIRCULATE given above, what happens (and explain why) when we evaluate
a. (circulate 'hello)

b. (circulate nil)

Define a function called MY-AND which acts like the Lisp AND function (but only takes 2 arguments) using only IF.

© Colin Allen & Maneesh Dhagat
March 2007