您的位置:首页 > 其它

SICP ex2-25 - ex 2-27

2016-05-16 08:42 399 查看
本节主要介绍了的一种树的数据结构

ex2-25要求给出一种deep-reserve 的程序使 ((1 2) 3 4)能够变为(4 3 (2 1) )

这个程序我们只需要加一个pair?检测,当为序列对时进行递归调用即可

ex2-26要求给出能将给定参数的元素合并至一个list中,

重点在于如何处理子序列对,我们这里采取了递归的方式,但是,这样会有一个问题,生成的子list的最后会有一个()我们又该如何处理这个空元素

我们另写一个程序,用来处理这种状况,这程序不难,与上一节的合并程序类似

ex2-27要求进行活动体的重量计算以及平衡判定

这里给出个建议,首先进行低级抽象,获得数个selector 不然后面光是car cdr的让人晕菜,另外注意((1 2) (3 4))中(3 4)应为(car (cdr x))切记,无论是左枝还是右枝,最左侧的operator都是car

用抽象的selector的话难度不大,不再赘述

以下是代码

(define (countatoms x)
(if (pair? x)
(+ (countatoms (car x)) (countatoms (cdr x)))
(if (null? x) 0 1)
))
(define (reserve x)
(let ((tmp (list)))
(define (iter a tmp)
(if (null? a) tmp
(iter (cdr a) (cons (car a) tmp))))
(iter x tmp)))
(define (deep-reserve x)
(let ((tmp (list)))
(define (iter a tmp)
(if (null? a) tmp
(if (pair? (car a)) (iter (cdr a) (cons (deep-reserve (car a)) tmp))
(iter (cdr a) (cons (car a) tmp)))))
(iter x tmp)))
(define (fringe x)
(define (merge x y)
(if (null? x) y
(cons (car x) (merge (cdr x) y))))
(if (null? x) ()
(if (pair? (car x))
(merge (fringe (car x)) (fringe (cdr x)))
(cons (car x) (fringe (cdr x))))))

(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 (get-weight x)
(if (pair? (branch-structure x)) (+ (get-weight (left-branch (branch-structure x))) (get-weight (right-branch (branch-structure x))))
(branch-structure x)))
(define (total-weight mobile)
(+ (get-weight (left-branch mobile)) (get-weight (right-branch mobile))))

(define (balance mobile)
(define (subbalance x)
(if (pair? (branch-structure x))
(and (subbalance (left-branch (branch-structure x))) (subbalance (right-branch (branch-structure x)))
(= (* (branch-length (left-branch x)) (get-weight (left-branch x)))
(* (branch-length (right-branch x )) (get-weight (right-branch x)))))
#t))
(and (subbalance (left-branch mobile)) (subbalance (right-branch mobile))
(= (* (branch-length (left-branch mobile)) (get-weight (left-branch mobile)))
(* (branch-length (right-branch mobile)) (get-weight (right-branch mobile))))))

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: