61 lines
1.2 KiB
Scheme
61 lines
1.2 KiB
Scheme
;(define (make-mobile left right)
|
|
;(list left right))
|
|
|
|
(define (make-mobile left right)
|
|
(cons left right))
|
|
|
|
;(define (make-branch length structure)
|
|
;(list length structure))
|
|
|
|
(define (make-branch length structure)
|
|
(cons length structure))
|
|
|
|
(define (left-branch mobile)
|
|
(car mobile))
|
|
|
|
;(define (right-branch mobile)
|
|
;(cadr mobile))
|
|
|
|
(define (right-branch mobile)
|
|
(cdr mobile))
|
|
|
|
(define (branch-length branch)
|
|
(car branch))
|
|
|
|
;(define (branch-structure branch)
|
|
;(cadr branch))
|
|
|
|
(define (branch-structure branch)
|
|
(cdr branch))
|
|
|
|
|
|
(define (mobile? m) (pair? m))
|
|
|
|
(define (branch-weight branch)
|
|
(let ((struct (branch-structure branch)))
|
|
(if (mobile? struct)
|
|
(total-weight struct)
|
|
struct)))
|
|
|
|
(define (total-weight mobile)
|
|
(+ (branch-weight (left-branch mobile))
|
|
(branch-weight (right-branch mobile))))
|
|
|
|
|
|
(define (torque branch)
|
|
(* (branch-length branch)
|
|
(branch-weight branch)))
|
|
|
|
(define (balanced? struct)
|
|
(cond ((null? struct) #t)
|
|
((not (mobile? struct)) #t)
|
|
(else
|
|
(let* ((l (left-branch struct))
|
|
(r (right-branch struct))
|
|
(l-struct (branch-structure l))
|
|
(r-struct (branch-structure r)))
|
|
(and (balanced? l-struct)
|
|
(balanced? r-struct)
|
|
(= (torque l) (torque r)))))))
|
|
|