SICP 习题2.29 二叉活动体

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

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

(define (left-branch x)
  (car x))

(define (right-branch x)
  (car (cdr x)))

(define (branch-length x)
  (car x))

(define (branch-structure x)
  (car (cdr x)))

(define (bsl x) (branch-structure (left-branch x)))
(define (bsr x) (branch-structure (right-branch x)))

(define (total-weight x)
  (if (pair? x)
    (+ (total-weight (bsl x)) (total-weight (bsr x)))
    x))

(define (bll x) (branch-length (left-branch x)))
(define (blr x) (branch-length (right-branch x)))

(define (balance? x)
    (cond ((and (pair? (bsl x)) (not (balance? (bsl x)))) #f)
          ((and (pair? (bsr x)) (not (balance? (bsr x)))) #f)
          (else (= (* (bll x) (total-weight (bsl x))) (* (blr x) (total-weight (bsr x)))))))

(define le (make-branch 1 6))
(define re (make-branch 2 3))

(define ae (make-branch 1 (make-mobile le re)))

(define x (make-mobile le re))

(newline)
(display (total-weight x))

(newline)
(display (total-weight (make-mobile re ae)))

(newline)
(display (total-weight (make-mobile ae ae)))

(newline)
(display (balance? (make-mobile ae ae)))

(newline)
(display (balance? (make-mobile le ae)))
将我的程序用cons改写修改了两个地方
(define (right-branch x)
  (cdr x))

(define (branch-structure x)
  (cdr x))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值