#lang racket
(define (make-mobile left right)
(list left right))
(define (left-branch mobile)
(car mobile))
(define (right-branch mobile)
(car (cdr mobile)))
(define (make-branch length structure)
(list length structure))
(define (branch-length branch)
(car branch))
(define (branch-structure branch)
(car (cdr branch)))
(define (total-weight branch)
(if (pair? (branch-structure branch))
(+ (total-weight (left-branch (branch-structure branch))) (total-weight (right-branch (branch-structure branch))))
(branch-structure branch)))
(define (branch-moment branch)
(* (branch-length branch) (total-weight branch)))
(define (balance? mobile)
(= (branch-moment (left-branch mobile))
(branch-moment (right-branch mobile))))
(define a-mobile (make-mobile (make-branch 1 2) (make-branch 3 4)))
(define b-mobile (make-mobile (make-branch 2 2) (make-branch 1 4)))
(define c-mobile (make-mobile (make-branch 2 a-mobile) (make-branch 1 b-mobile)))
(define d-mobile (make-mobile (make-branch 2 a-mobile) (make-branch 1 b-mobile)))
(define e-mobile (make-mobile (make-branch 2 c-mobile) (make-branch 1 d-mobile)))
(define f-mobile (make-mobile (make-branch 2 c-mobile) (make-branch 1 a-mobile)))
(total-weight (left-branch e-mobile))
(balance? e-mobile)
(balance? f-mobile)
运行结果
12
#t
#f
改变活动体的表示,只需要改变选择过程就能完成改造。
(define (make-mobile left right)
(cons left right))
(define (left-branch mobile)
(car mobile))
(define (right-branch mobile)
(cdr mobile))
(define (make-branch length structure)
(cons length structure))
(define (branch-length branch)
(car branch))
(define (branch-structure branch)
(cdr branch))