理系学生日記

おまえはいつまで学生気分なのか

問題3-12 (3.3.1 Mutable List Structure)

set-car! と set-cdr! でリスト構造を変更することができるよ!!というおはなし.

append と append! が以下のように定義されているとき,

(define (append x y)
  (if (null? x)
      y
      (cons (car x) (append (cdr x) y))))
(define (append! x y)
  (set-cdr! (last-pair x) y)
  x)
(define x (list 'a 'b))
(define y (list 'c 'd))
(define z (append x y))
(cdr x) ; (b)

こうなるのは,append だと x の内容が変更されないから.

(define w (append! x y))
(cdr x) ; (b c d)

もちろん,append! だと x の内容そのものが変わるので,出力も変わる.