您的位置:首页 > 其它

层次性结构

2016-05-08 23:27 239 查看
(define (append a b)
(if (null? a)
b
(cons (car a) (append (cdr a) (cons (car a) b)))))
(define nil (list))
(define (count-leaves x)
(cond ((null? x) 0)
((not (pair? x)) 1)
(else (+ (count-leaves (car x))
(count-leaves (cdr x))))))
;;
(define (reverse l)
(define (reverse-iter tmp ans)
(if (null? tmp)
ans
(reverse-iter (cdr tmp) (cons (car tmp) ans))))
(reverse-iter l nil))
;2.27
(define (deep-reverse l)
(define (deep-reverse-in tmp ans)
(cond ((null? tmp) ans)
((pair? (car tmp))
(deep-reverse-in (cdr tmp)
(cons (deep-reverse-in (car tmp) nil) ans)))
(else (deep-reverse-in (cdr tmp)
(cons (car tmp) ans)))))
(deep-reverse-in l nil))
;2.28
(define (fringe t)
(define (fringe-in tmp ans)
(cond ((null? tmp) ans)
((not (pair? tmp)) (cons tmp ans))
(else (fringe-in (car tmp) (fringe-in (cdr tmp) ans)))))
(fringe-in t nil))
(fringe (list (list 1 (list 5 6 7)) (list 3 4) 8))
;2.29
(define (make-mobile left right)
(cons left right))
(define (make-branch length structure)
(cons length structure))
(define (left-branch x)
(car x))
(define (right-branch x)
(cdr x))
(define (branch-length x)
(car x))
(define (branch-structure x)
(cdr x))
(define (total-weight t)
(if (not (pair? t))
t
(+ (total-weight (branch-structure (left-branch t)))
(total-weight (branch-structure (right-branch t))))))
(define (mobile-balance t)
(or (not (pair? t))
(and (mobile-balance (branch-structure (left-branch t)))
(mobile-balance (branch-structure (right-branch t)))
(= (* (total-weight (branch-structure (left-branch t)))
(branch-length (left-branch t)))
(* (total-weight (branch-structure (right-branch t)))
(branch-length (right-branch t)))))))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: