(wat-aro)

無職から有職者にランクアップしました

SICP 問題 2.29

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

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

;; a
(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
(define (total-weight mob)
  (if (pair? mob)
      (+ (total-weight (branch-structure (left-branch mob)))
         (total-weight (branch-structure (right-branch mob))))))

;; c
(define (balanced? mob)
  (if (pair? mob)
      (and (= (* (branch-length (left-branch mob))
                 (total-weight (left-branch mob)))
              (* (branch-length (right-branch mob))
                 (total-weight (right-branch mob))))
           (balanced? (left-branch mob))
           (balanced? (right-branch mob)))
      #f))

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

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