SICP 2.25~2.29习题答案

这一节难度开始加大,有一些答案是借鉴了别人才做出来的。
;; 2.25
(define list1 (list 1 3 (list 5 7) 9))
;(car (cdr (car (cdr (cdr list1)))))

(define list2 (list (list 7)))
;(car (car list2))

(define list3 (list 1 (list 2 (list 3 (list 4 (list 5 (list 6 7)))))))
;(car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr list3))))))))))))

;; 2.26
(define x (list 1 2 3))
(define y (list 4 5 6))
;(append x y)
;(cons x y)
;(list x y)

;; 2.27
(define (deep-reverse items)
(if (null? items) nil
(append (deep-reverse (cdr items))
(cons (if (pair? (car items)) (deep-reverse (car items))
(car items))
nil))))

(define x (list (list 1 2) (list 3 4)))
;(deep-reverse x)

(define (count-leaves x)
(cond ((null? x) 0)
((not (pair? x)) 1)
(else (+ (count-leaves (car x))
(count-leaves (cdr x))))))

;; 2.28
(define (fringe items)
(cond ((null? items) nil)
((pair? items) (append (fringe (car items))
(fringe (cdr items))))
(else (list items))))

(define x (list (list 1 2) (list 3 4)))
;(fringe x)
;(fringe (list x x))

;; 2.29
;(define (make-mobile left right) (list left right))
;(define (make-branch length structure) (list length structure))
;(define (left-branch mobile) (car mobile))
;(define (right-branch mobile) (car (cdr mobile)))
;(define (branch-length branch) (car branch))
;(define (branch-structure branch) (car (cdr branch)))

(define (make-mobile left right) (cons left right))
(define (make-branch length structure) (cons length structure))
(define (left-branch mobile) (car mobile))
(define (right-branch mobile) (cdr mobile))
(define (branch-length branch) (car branch))
(define (branch-structure branch) (cdr branch))

(define (mobile? structure) (pair? structure))

(define (branch-weight branch)
(let ((structure (branch-structure branch)))
(if (mobile? structure) (total-weight structure)
structure)))

(define (total-weight mobile)
(+ (branch-weight (left-branch mobile))
(branch-weight (right-branch mobile))))

(define (weight branch)
(* (branch-length branch) (branch-weight branch)))

(define (balance? mobile)
(let ((left (left-branch mobile))
(right (right-branch mobile)))
(and (= (weight left) (weight right))
(if (mobile? (branch-structure left)) (balance? left) #t)
(if (mobile? (branch-structure right)) (balance? right) #t))))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值