<< Previous exercise (2.28) | Index | Next exercise (2.30) >>
; balanced? predicate (define (balanced? m) (define (total-weight m) (define (branch-weight b) (let ((s (branch-structure b))) (if (mobile? s) (total-weight s) s))) (let* ((l (left-branch m)) (r (right-branch m)) (lw (branch-weight l)) (rw (branch-weight r))) (if (or (< lw 0) (< rw 0)) -1 (let ((lt (* (branch-length l) lw)) (rt (* (branch-length r) rw))) (if (= lt rt) (+ lw rw) -1))))) (> (total-weight m) -1))
Another form of (balanced? mobile)
(define (balanced? mobile)
(define (torque branch)
;find torque on this particular branch
(if (is-mobile? (branch-struct branch))
(* (branch-len branch)
(total-weight (branch-struct branch)))
(* (branch-len branch)
(branch-struct branch))))
;nested AND for each branch pair
(and (= (torque (left-branch mobile))
(torque (right-branch mobile)))
;if more branches, repeat balanced? - if a leaf is
;reached, return #t
(if (is-mobile? (branch-struct (left-branch mobile)))
(balanced? (branch-struct (left-branch mobile)))
#t)
(if (is-mobile? (branch-struct (right-branch mobile)))
(balanced? (branch-struct (right-branch mobile)))
#t)))
jz