SICP 2.27 2.28 2.29
SICP 2.27 2.28 2.29

SICP 2.27 2.28 2.29
• 发表于 2年前
• 阅读 2
• 收藏 0
• 评论 0

2.27

(define (deep-reverse lst)
(define (x-reverse l r)
(cond ((null? l) r)
((pair? (car l)) (x-reverse (cdr l) (cons (x-reverse (car l) '()) r)))
(else (x-reverse (cdr l) (cons (car l) r)))))
(x-reverse lst '()))

2.28

(define (my-fringe lst)
(define (x-fringe l res)
(cond ((pair? l) (x-fringe (car l) (x-fringe (cdr l) res)))
((null? l) res)
(else (cons l res))))
(x-fringe (car lst) (x-fringe (cdr lst) '())))

2.29

(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 (is-branch? x) (number? (branch-length x)))
(define (total-weight x)
(if (is-branch? x)
(branch-structure x)
(+ (total-weight (left-branch x))
(total-weight (right-branch x)))))

(define (get-moment x)
(* (branch-length x) (branch-structure x)))
(define (total-moment x)
(if (is-branch? x)
(get-moment x)
(total-moment (right-branch x)))))
(define (mobile-equilibrium? x)
(if (is-branch? x)
#t
(let ((left (left-branch x))
(right (right-branch x)))
(if (= (total-moment left) (total-moment right))
(and (mobile-equilibrium? left)
(mobile-equilibrium? right))
#f))))

×