1 (define x (list 'a 'b)) 2 3 (define y (list 'c 'd)) 4 5 (define z (append x y)) 6 7 (cdr x) 8 9 (define (append! x y) 10 (set-cdr! (last-pair x) y) 11 x) 12 13 (define (last-pair x) 14 (if (null? (cdr x)) 15 x 16 (last-pair (cdr x)))) 17 18 (define z1 (append! x y)) 19 20 (cdr z1)
x----->[ * ]----->[ * ]----->( )
| |
v v
a b
y----->[ * ]----->[ * ]----->( )
| |
v v
c d
z----->[ * ]----->[ * ]----->[ * ]----->[ * ]----->( )
| | | |
v v v v
a b c d
z1------+
|
v
x----->[ * ]----->[ * ]-----+
| | |
v v |
a b |
|
+-----------------+
|
v
y----->[ * ]----->[ * ]----->( )
| |
v v
c d
1 (define (make-cycle x) 2 (set-cdr! (last-pair x) x) 3 x) 4 5 (define z2 (make-cycle (list 'a 'b 'c))) 6 ;z2 7 ;(last-pair z2)
+---------------------------+
| |
v |
z2----->[ * ]----->[ * ]----->[ * ]-----+
| | |
v v v
a b c
如果求(last-pair z2)将会无限循环下去
1 ;;;;;;;;3.14 2 3 (define (mystery x) 4 (define (loop x y) 5 (if (null? x) 6 y 7 (let ((temp (cdr x))) 8 (set-cdr! x y) 9 (loop temp x)))) 10 (loop x '())) 11 12 (define v '(a b c d )) 13 14 (define w (mystery v)) 15 16 (cdr v)
可以发现这就是reverse的修改版
v-----------------------------------------+
|
v
w----->[ * ]----->[ * ]----->[ * ]----->[ * ]----->( )
| | | |
v v v v
d c b a