本節主要介紹了的一種樹的數據結構
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))))))