Ex 2.29
かなり悩んでいる。とりあえず経過を。
a.
(define (left-branch m) (car m)) (define (right-branch m) (car (cdr m))) (define (branch-length b) (car b)) (define (branch-structure b) (car (cdr b)))
b.
(define (total-weight m) (define (weight b) (let ((s branch-structure b))) (if (not (pair? s)) s (total-weight s)))) (+ (weight (left-branch m)) (weight (right-branch m))))
-
-
- -
-
この b. の定義だとうまくいかないので次のように修正:
(define (total-weight m) (if (not (pair? m)) m (+ (total-weight (branch-structure (left-branch m))) (total-weight (branch-structure (right-branch m))))))
そして c. は次のとおり:
(define (balanced? m) (define (rot-pow b) (* (branch-length b) (total-weight (branch-structure b)))) (if (not (pair? m)) true (let ((l (left-branch m)) (r (right-branch m))) (and (= (rot-pow l) (rot-pow r)) (balanced? (branch-structure l)) (balanced? (branch-structure r))))))
d. については right-branch および branch-structure を以下のように変更するだけでよく、 total-weight および balanced? には何ら手を加えずに利用できる。
(define (right-branch m) (cdr m)) (define (branch-structure b) (cdr b))
ちょっと気になるのは、 pair? で構造をテストしていること。これでたどれない構造によってデータを構成した場合、プログラム全体を修正せざるをえないよな。