SICP問題3.12
箱とポインタは
┌─┬─┐ │・│・│ → □□ └─┴─┘ ┌─┬─┐ │・│/│ → □■ └─┴─┘
で表記してます。
2.2.1節のappend(教科書で定義)
(define (append x y) (if (null? x) y (cons (car x) (append (cdr x) y))))
append!, last-pair(教科書で定義)
(define (append! x y) (set-cdr! (last-pair x) y) x) (define (last-pair x) (if (null? (cdr x)) x (last-pair (cdr x))))
以下の定義について(cdr x)の応答が何かを示す
(define x (list 'a 'b)) (define y (list 'c 'd)) (define z (append x y)) z ; (a b c d)
z の箱とポインタ図は以下のようになる
z→□□→□□→□■ ↓ ↓ │ x→□□→□■ │ ↓ ↓ │ a b ↓ y→□□→□■ ↓ ↓ c d
これより
(cdr x) ; (b)
となる
(define w (append! x y)) w ; (a b c d)
w の箱とポインタ図は以下のようになる
w┐ ↓ x→□□→□□┐ ↓ ↓ │ a b ↓ y→□□→□■ ↓ ↓ c d
これより
(cdr x) ; (b c d)
となる