問題2.29 – SICP(計算機プログラムの構造と解釈)その44

問題2.29

(define (make-mobile left right)
  (list left right))

(define (make-branch length structure)
  (list length structure))

a. left-branchright-branchbranch-lengthbranch-structure

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

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

(define (branch-length branch)
  (car branch))

(define (branch-structure branch)
  (car (cdr branch)))

b. total-weight

(define (branch-weight branch)
  (let ((st (branch-structure branch)))
   (cond ((null? branch) 0)
         ((not (pair? st)) st)
         (else
           (total-weight st)))))

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

c. balanced?

(define (torque branch)
  (let ((st (branch-structure branch)))
       (if (pair? st)
           (+ (torque (left-branch st)) (torque (right-branch st)))
           (* (branch-length branch) (branch-weight branch)))))

(define (balanced? mobile)
  (= (torque (left-branch mobile)) (torque (right-branch mobile))))

d. make-mobilemake-branchcons を使って表現した場合

手続き right-branchbranch-structure を次のように変更すればよい。

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

(define (branch-structure branch)
  (cdr branch))
計算機プログラムの構造と解釈
ジェラルド・ジェイ サスマン ジュリー サスマン ハロルド エイブルソン
ピアソンエデュケーション
売り上げランキング: 6542
«
»