计算机程序的构造和解释 练习题2.29

#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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值