理系学生日記

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

問題3-16 (3.3.1 Mutable List Structure)

pair の数が 3 個なのにも関わらず,count-pair の返り値が 3,4,7,制御を返さないという 4 パターンの引数を考えろという話.

(define (count-pairs x)
  (if (not (pair? x))
      0
      (+ (count-pairs (car x))
	 (count-pairs (cdr x))
	 1)))

最初勘違いしててとまどったけど,ようやくスッキリした.

(define return-three (cons (cons 'a 'b) (cons 'c 'd)))
(count-pairs return-three) ; 3

(define pair1 (cons 'a 'b))
(define return-four (cons pair1 (cons pair1 'd)))
(count-pairs return-four) ; 4

(define pair2 (cons pair1 pair1))
(define return-seven (cons pair2 pair2))
(count-pairs return-seven) ; 7

(define return-not-at-all (cons (cons 'a 'b) (cons 'c 'd)))
(set-cdr! (car return-not-at-all) return-not-at-all)
(count-pairs return-not-at-all)