CS 3723/3721 Programming Languages
Lisp Recitation 1: Basics and Functions


Lisp:

Basics:

  1. Try out Lisp on the CS computers by logging in and typing to activate lisp, and to quit. (The commonly used (exit) does not work.)
  2. Try out numeric computations. Do and calculate
  3. Try Use setq to assign and similarly for b and c, to give lengths of the sides of a triangle. Then set and similarly for beta and gamma, to give the three angles of the triangle. Finally set
  4. Try out car, cdr, and cons, using the following examples: Now try
  5. Try out append and list:

Functions:

    For this recitation and the next one, your Lisp functions should not have any iterative constructs (such as prog, do, etc.) but all iteration should be done with recursion. Inside functions you should not make use of the setf or setq functions.

  1. Consider the follwing lisp function (the lisp functions defun and cond will be discussed in class): Save this function as a file named "fact.l". Then try out
  2. Mimic the factorial function above to define a function harmonic, where (harmonic n) returns the value
    1. First use the operator / with integers, so that the answers are rational numbers. [Try out n = 10, 20. As a check, the value of (harmonic 10) should be 7381/2520.]
    2. Then rewrite the harmonic function using constants with a decimal point to force Lisp to use floating point numbers. [Now as a check the value of (harmonic 10) should be 2.9289682539682538.]
    3. It turns out that (harmonic n) is approximately equal to log(n) + g, where g = 0.5772156649. . . is known as Euler's constant. Use Lisp to check the accuracy of this approximation for n = 10, 100, 1000. (Here log is the logarithm base e, which is available in Lisp under the name log.) [The accuracy should be better than 1/n.]

  3. Write a recursive function fibonacci that will return the nth fibonacci number F[n], where [For reference, (fibonacci 10) should return 55, (fibonacci 20) returns 6765 after a few seconds, and (fibonacci 30) returns 832040 after as much as several minutes. Why do you think this takes so long?]
  4. Write a recursive function maxvec that finds the maximum of a simple list of numbers. [Hint: if the cdr is nil, just return the car, and otherwise return the maximum of the car and of maxvec applied to the cdr. For example, (maxvec '(2 5 6 3)) returns 6.]
  5. Try out the function reverse in Lisp: Define your own function reverse1 which will behave the same way as reverse, reversing the order of elements of a list at the top level only. [Hint: Invoke reverse1 recursively on the cdr and tack on the car at the end.]
  6. Define a function count-atoms that will count the number of atoms in a list, at all levels. For example (count-atoms '(a (b c) (d (e) f))) should return 6. [Hint: Mimic list-atoms from class.]


Revision date: 2002-10-27. (Please use ISO 8601, the International Standard Date and Time Notation.)