CSCI 330 Quiz 1 Sample Solutions: basic lisp
Question 1 [4 marks]
This question has two parts (part b is on the reverse side of the page).
Part a:
A math expression of five variables (a,b,c,d,e) is shown below in
C-style syntax. Provide an equivalent lisp expression.
((a + (b - c)) / sqrt((a*e)+(b*d)))
Sample solution
(/ (+ a (- b c)) (sqrt (+ (* a e) (* b d))))
Part b:
Pseudo-code is used below to describe a sequence of traditional if-else if-else statements.
Assuming the variable x has already been declared and initialized,
provide equivalent lisp code using either a single cond statement or a nested-if block.
if x is a string then return the length of x
else if x is a real then return the sum of x's square and its square root
else if x is not a list then display "cannot process" and return false
else if the length of x is at least 2 then return the second element of x
else return true
Sample solution
(cond
((stringp x) (length x))
((realp x) (+ (* x x) (sqrt x)))
((not (listp x)) (format t "cannot process"))
((>= (length x) 2) (cadr x))
(t t))
Question 2 [4 marks]
Write a lisp function, named trip, that takes a single parameter N and
recursively computes and returns the Nth triponacci number.
(trip N) is defined as follows:
- if N is not an integer or if N < 4 then (trip N) is 1
- otherwise (trip N) is the sum of the three previous (trip N) numbers
Thus the triponacci sequence goes: 1, 1, 1, 3, 5, 9, 17, 31, 57, etc.
Sample solution
(defun trip (N)
(cond
((not (integerp N)) 1)
((< N 4) 1)
(t (+ (trip (- N 1)) (trip (- N 2)) (trip (- N 3))))))
Question 3 [4 marks]
Study the lisp function below then show the output it would produce and
the value it would return if the user made the call (q3 1.5 4)
and then entered value -1 for the first read, 2 for the second,
"foo" for the third, and 0.3 for the fourth.
(defun q3 (v i)
(format t "(~A ~A)~%" v i)
(let ((x (read)))
(cond
((not (realp v)) (format t "bad v: ~A~%" v))
((not (integerp i)) (format t "bad i: ~A~%" i))
((< i 1) v)
((= i 1) (+ v x))
((not (realp x)) (q3 v (- i 1)))
(t (q3 (+ v x) (- i 1))))))
Sample solution
output discussion
(1.5 4) ; from format for original call
; then reads -1 for x
; does default case recursive call using v=v+x, i=i-1, so (q3 0.5 3)
(0.5 3) ; from format for second call
; then reads 2 for x
; does default case recursive call, i.e. (q3 2.5 2)
(2.5 2) ; from format for third call
; then reads "foo" for x
; does x not real recursive call, same v but i=i-1
(2.5 1) ; from format for fourth call
; then reads 0.3 for x
; does i=1 base case, returning v+x
thus returns 2.8