ANSI Common Lisp 第二章答案

本文档记录了作者学习ANSI Common Lisp过程中的章节练习解答,涵盖了基本语法、递归与迭代函数实现等内容,提供了丰富的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开始看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)))))))

  
  

-----------------------------------

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值