Open Source WEB

##(link2sicp "book-Z-H-15.html#%_thm_2.29" "Exercise 2.29")

解答例

a.

(define (left-branch mobile) (car mobile))
(define (right-branch mobile) (car (cdr mobile)))

(define (branch-length branch) (car branch))
(define (branch-structure branch) (cadr branch))

b.

(define (total-weight mobile)
  (let ((left (left-branch mobile))
        (right (right-branch mobile)))
    (+ (branch-weight left)
       (branch-weight right))))

(define (branch-weight branch)
  (let ((structure (branch-structure branch)))
    (if (not (pair? structure))
        structure
        (total-weight structure))))

c.

(define (balanced? mobile)
  (if (balanced-mobile? mobile) #t #f))
      
(define (balanced-mobile? mobile)
  (let ((left (left-branch mobile))
        (right (right-branch mobile)))
    (let ((left-weight (balanced-branch? left)))
      (and left-weight
           (let ((right-weight (balanced-branch? right)))
             (and right-weight
                  (= (* (branch-length left) left-weight)
                     (* (branch-length right) right-weight))
                  (+ left-weight right-weight)))))))

(define (balanced-branch? branch)
  (let ((structure (branch-structure branch)))
    (if (pair? structure)
        (balanced-mobile? structure)
        structure)))

d. 選択子 right-branch、branch-structure を変更するだけでよい。

コード

##(sicp-answer-code "ex-2.29.scm")

このサイトは、 IPA の「平成15年度オープンソフトウエア活用基盤整備事業」 の委託事業として開発されたKahuaで試験的に運用しております。

Copyright (c) 2004-2007 株式会社タイムインターメディア About Us