欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SICP 2.25~2.29习题答案

程序员文章站 2022-07-14 10:49:30
...
这一节难度开始加大,有一些答案是借鉴了别人才做出来的。
;; 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))))

相关标签: Mobile Scheme