scheme 层次性结构
前文提到scheme的表是一种序对的层次性结构,本节对层次性结构进行一点扩展,通过树状结构来表达该结构。
练习2.24 求值(list 1 (list 2 (list 3 4))),给出对应的层次性结构。
求值部分就扔进去就完了(1 (2 (3 4)))
结构大概是(1 (2 (3 4))) → (1)&(2 (3 4))→ (2) (3 4)→(3) (4)
练习2.25 给出能从下面各表取出7的car和cdr组合
单纯的car和cdr的运用:
(car (cdr (car (cdr (cdr (list 1 3 (list 5 7) 9))))))
(car (car (list (list 7))))
(car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (list 1 (list 2 (list 3 (list 4 (list 5 (list 6 7))))))))))))))))))
练习2.26 几个序对组合式的简单表达
假定已将x和y定义为如下两个表:
(define x (list 1 2 3))
(define y (list 4 5 6))
解释器对如下的表达式打印出什么结果:
(append x y)
(1 2 3 4 5 6)
(cons x y)
((1 2 3) 4 5 6)
(list x y)
((1 2 3) (4 5 6))
练习2.27 修改练习2.18中做的reverse过程,得到一个deep-reverse过程,反转表的过程中需将其中的子树也发转过来
其实就是在reverse过程中判断一下car x是否为序对,如果是就再重复一遍reverse过程。
点击查看代码
;reverse过程
(define (reverse x)
(if (null? x)
nil
(append (reverse (cdr x)) (list (car x)))
)
)
;在reverse过程基础上增加判断
(define (reverse-deep x)
(if (null? x)
nil
(append (reverse-deep (cdr x))
(if (pair? (car x))
(list (reverse-deep (car x)))
(list (car x))
)
)
)
)
点击查看代码
(define (fringe x)
(if (null? x)
nil
(append
;判断取出的元素是否为序对,如果是则再遍历排列一遍
(if (pair? (car x))
(fringe (car x))
(list (car x)))
(fringe (cdr x)))))
点击查看代码
(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 (total-weight mobile)
(if (not (pair? mobile))
mobile
(+
(branch-weight (left-branch mobile))
(branch-weight (right-branch mobile)))
)
)
(define (branch-weight branch)
(if (pair? branch)
(if (pair? (branch-structure branch))
(total-weight (branch-structure branch))
(branch-structure branch))
branch
)
)
点击查看代码
;求某一分支的力矩
(define (branch-torque branch)
(* (branch-length branch)
(branch-weight branch)))
;判断分支是否平衡
(define (branch-balanced? branch)
(if (pair? (branch-structure branch))
(balanced? (branch-structure branch))
#t
)
)
;判断二叉体是否平衡
(define (balanced? mobile)
(and ( = (branch-torque (left-branch mobile))
(branch-torque (right-branch mobile)))
(branch-balanced? (left-branch mobile))
(branch-balanced? (right-branch mobile))
)
)

浙公网安备 33010602011771号