SCXT 350
Exercise set #1 Amswers
1. Write a LISP expression which will calculate
(3 + 2) * (10 - 3)
(* (+ 3 2) (- 10 3))
2. Write LISP expressions which will return the second item in a list lst. The third item in the list.
(car (cdr lst)) (car (cdr (cdr lst)))
3. Write a function which will return the largest of three numbers
(defun max3 (a b c) (if (and (> a c) (> a b)) a (if (> b c) b c)))
4. Write a function which will calculate the average of two numbers
(defun avg2 (a b) (/ (+ a b) 2.0))
5. Write a function which will take a list (with at least two elements) and return the list with the first two elements swapped. For example, (swapper '(a b c d e)) should return (b a c d e).
(defun swapper (lst) (cons (car (cdr lst)) (cons (car lst) (cdr (cdr lst)))))
6. Write a function to calculate the n'th Fibonacci number according to the following rule: If n is less than 3, then FIB(n) = 1. If n is bigger than or equal to 3, then FIB(n) = FIB(n-1) + FIB(n-2). Try using the trace function on this when you get it working.
(defun fib (n) (if (< n 3) 1 (+ (fib (- n 1)) (fib (- n 2)))))
7, (For students who have had at least a semester of computer science: Write a function CountAtoms which will count the number of atoms in a list. For example, (CountAtoms '(a b c)) = 3 and (CountAtoms '((a b) c (d (e f)))) = 6
(defun countatoms (lst) (if (null lst) 0 (if (atom (car lst)) (+ 1 (countatoms (cdr lst))) (+ (countatoms (car lst)) (countatoms (cdr lst))))))
In our lab on Monday, try your solutions out. On Friday, Sept. 15, turn in (in class) your written solutions to problems 1 - 6.