习题2.17,直接利用list-ref和length过程
<!---->
(define (last
-
pair items)
(list (list
-
ref items (
-
(length items)
1
))))
习题2.18,采用迭代法
<!---->
(define (reverse
-
list items)
(define (reverse
-
iter i k)
(
if
(
null
?
i) k (reverse
-
iter (cdr i) (cons (car i) k))))
(reverse
-
iter items ()))
习题2.20,如果两个数的奇偶相同,那么他们的差模2等于0,根据这一点可以写出:
<!---->
(define (same
-
parity a . b)
(define (same
-
parity
-
temp x y)
(cond ((
null
?
y) y)
((
=
(remainder (
-
(car y) x)
2
)
0
)
(cons (car y) (same
-
parity
-
temp x (cdr y))))
(
else
(same
-
parity
-
temp x (cdr y)))))
(cons a (same
-
parity
-
temp a b)))
利用了基本过程remainder取模
习题2.21,递归方式:
<!---->
(define (square
-
list items)
(
if
(
null
?
items)
items
(cons (square (car items)) (square
-
list (cdr items)))))
利用map过程:
<!---->
(define (square
-
list items)
(map square items))
习题2.23,这与ruby中的each是一样的意思,将操作应用于集合的每个元素:
<!---->
(define (
for
-
each proc items)
(define (
for
-
each
-
temp proc temp items)
(
if
(
null
?
items)
#t
(
for
-
each
-
temp proc (proc (car items)) (cdr items))))
(
for
-
each
-
temp proc
0
items))
最后返回true
习题2.24,盒子图就不画了,麻烦,解释器输出:
<!---->
Welcome to DrScheme, version
360
.
Language: Standard (R5RS).
>
(list
1
(list
2
(list
3
4
)))
(
1
(
2
(
3
4
)))
树形状应当是这样
.
/\
/ \
1 .
/\
/ \
2 .
/\
/ \
3 4
习题2.25,
第一个list可以表示为(list 1 3 (list 5 7) 9)
因此取7的操作应当是:
<!---->
(car (cdr (car (cdr (cdr (list
1
3
(list
5
7
)
9
))))))
第二个list表示为:(list (list 7))
因此取7操作为:
<!---->
(car (car (list (list
7
))))
第三个list可以表示为:
<!---->
(list
1
(list
2
(list
3
(list
4
(list
5
(list
6
7
))))))
因此取7的操作为:
<!---->
(define x (list
1
(list
2
(list
3
(list
4
(list
5
(list
6
7
)))))))
(car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr x))))))))))))
够恐怖!-_-
习题2.26,纯粹的动手题,就不说了
习题2.27,在reverse的基础上进行修改,同样采用迭代,比较难理解:
<!---->
(define (deep
-
reverse x)
(define (reverse
-
iter rest result)
(cond ((null? rest) result)
((
not
(pair? (car rest)))
(reverse
-
iter (cdr rest)
(cons (car rest) result)))
(
else
(reverse
-
iter (cdr rest)
(cons (deep
-
reverse (car rest)) result)))
))
(reverse
-
iter x ()))
习题2.28,递归,利用append过程就容易了:
<!---->
(define (finge x)
(cond ((pair? x) (append (finge (car x)) (finge (cdr x))))
((null? x) ())
(
else
(list x))))