开始看ANSI Common Lisp并且做课后答案,每章的答案都是运行测试过的奥。
chapter 2
1, (a) 14
(b) (1 5)
(c) (if ( listp 1) (+ 1 2 ) ( + 3 4))
7
(d) ( list (and ( listp 3) t ) (+ 1 2))
(NIL 3)
2,
(cons 'a '(b c))
(cons 'a (cons'b (cons 'c nil)))
(cons (car '(a b c)) (cdr '(a b c)))
3
(defun fourth-element(lst)
(car (cdr (cdr (cdr lst)))))
4
(defun greater(x y)
(if (> x y)
x
y))
5
(a)
test if a list x is not null and x has nil element.
(defun enigma (x)
(and (not (null x))
(or (null (car x))
((enigma (cdr x)))))
(b)
if x is not an element of y, return nil
else return the position of x in y, 0 denotes the first position.
(defun mystery (x y)
(if (null y)
nil
(if (eql (car y) x)
0
(let ((z (mystery x (cdr y))))
(and z (+ z 1))))))
6
(a) car
(b) or
(c) apply
7
(defun test(lst)
(if (null lst)
nil
(if (listp (car lst))
t
(test (cdr lst)))))
8
(a)
iterative
(defun print-dots(x)
(do ((i 0 (+ i 1)))
((eq i x) (format t "~%done"))
(format t ". ")))
recursive function:
(defun print-dots-recursive(x)
(if (> x 0)
(list (format t ". ") (print-dots-recursive (- x 1)))
(format t "~%done")))
(b)
iterative
(defun count-a-iterative (lst)
(let ((i 0))
(do ((tmp lst (cdr tmp)))
((null tmp) i)
(if (eq (car tmp) 'a)
(setf i (+ i 1))))))
(defun count-a-recursive (lst)
(if (null lst)
0
(if (eq (car lst) 'a)
(+ 1 (count-a-recursive (cdr lst)))
(count-a-recursive (cdr lst)))))
9
(a)
because (remove nil lst) does not change lst.
(defun summit (lst)
(apply #'+ (remove nil lst)))
(b)
there is no terminate condition
(defun summit (lst)
(if (null lst)
0
(let ((x (car lst)))
(if (null x)
(summit (cdr lst))
(+ x (summit (cdr lst)))))))
-----------------------------------