摘自 《Lisp语言- 陈光喜》
P28 1.10 习题
1、写出下列数学式子中的中缀表达式
(+ (+ (* 3 3) (* (- (/ (* 17 5) 6) 4) 8)) 49)
(+ (* 2 (sin (- (+ (/ x y) e) (* 3 y)))) (* 45 (* x x)))
(+ (+ (+ (+ (+ (* (* a (* (* x x) x)) y) (* (* b (* x x)) (* y y))) (* (* c x) y)) (* d x)) (* e y)) f)
2、给出下列表达式的值,并写出其数学形式
数学形式:
表达式值:2
数学形式:9-2SQRT(25)
表达式值:-1
3、利用car和cdr写一个函数给出表的第5个元素
(1)不用循环
CL-USER> (defun fifthof(list)
(car (cdr (cdr (cdr (cdr list))))))
FIFTHOF
CL-USER> (fifthof '(1 2 3 4 5 6 7 8 9 10))
5
CL-USER> (fifthof '(a b c d e f))
E
CL-USER> (fifthof '( 1 2 3))
NIL
(2)用循环
CL-USER> (defun fifthof2(list)
(car (do ((a 1 (+ a 1)))
((> a 4) list)
(setf list (cdr list))
)
)
)
FIFTHOF2
CL-USER> (fifthof2 '(1 2 3 4 5 6 7 8 9))
5
CL-USER> (fifthof2 '(1 2 3))
NIL
4、写函数,计算:
1)两个数中的最大值
CL-USER> (defun mymax(p q)
(if (> p q) p q))
MYMAX
CL-USER> (mymax 3 4)
4
CL-USER> (mymax 5 5)
5
2)三个数中的最小值
CL-USER> (defun mymin(p q r)
(if (< p q) (if (< p r) p r) (if (< q r) q r)))
MYMIN
CL-USER> (mymin 1 2 3)
1
CL-USER> (mymin 4 5 6)
4
CL-USER> (mymin 83 2 89)
2
3)逆序输出三个数
CL-USER> (defun desc(a b c)
(format t "~A ~A ~A" c b a))
DESC
CL-USER> (desc 1 2 3)
3 2 1
5、 写一个函数计算嵌套表有几层。如(1 2 ( 3 (4 5 (a (c 3) 2 ( 9 0) ) d 1) (6 a)) (w r (f 5) 3))层数为 5
CL-USER> (defun deep(obj)
(if (atom obj)
0
(1+ (apply #'max (mapcar #'deep obj)))))
DEEP
CL-USER> (deep '(1 2 3))
1
CL-USER> (deep '(1 2 (3 (4 5 (a (c 3) 2 (9 0)) d 1)(6 a))(w r (f 5) 3)))
5
注:以上答案来自百度知道☺
6. 说明下述程序的功能
此题不知道答案,敲了一遍,返回都是 NIL
(defun eb(x)
(and (not (null x))
(or (null (car x))
(eb (cdr x)))))
7、写一个递归函数,统计一个表中指定字符出现的次数
CL-USER> (defun findxcount(list x)
(if (not (listp list)) (format t "sorry,you need a list")
(let ((a (car list)) (z (cdr list))) (if (atom z) (if (eq a x) 1 0) (if (eq a x) (+ 1 (findxcount z x)) (findxcount z x))))))
FINDXCOUNT
CL-USER> (findxcount '(1 2 3) 1)
1
CL-USER> (findxcount '(1 2 3 4 55 6 55 45 55 67 555 44 55) 55)
4
CL-USER> (findxcount '(1 2 3 4 5 6 7 8 9) 34)
0
8、写一个函数,需要一个表作为参数,取出该表 中的元素也是是表的那些元素,若不含表,打印提示。
CL-USER> (defun findlistof(a)
(if (not (listp a)) (format t "sorry, you need a list")
(dolist (v a)
(if (listp v) (format t "~S" v)))))
FINDLISTOF
CL-USER> (findlistof '(1 2 3 '(4 5) 6 '(7 8 9) 0))
'(4 5)'(7 8 9)
NIL
CL-USER> (findlistof '(1 2 3 '(9 0)))
'(9 0)
NIL
CL-USER> (findlistof 2)
sorry, you need a list
NIL
CL-USER>