練習2.68
先要導入練習2.67中的sample-tree。這道題要求我們寫出能夠根據給定的樹產生出給定符號的2進制位表的函數encode-symbol,這個函數還要能夠在遇到未在樹中出現的符號時報錯。這個函數將要在給定的樹中查找給定符號的葉子節點,并記錄下尋覓進程中的左右方向,固然了,如書中所說,向左則用0,向右則用1。因此該函數可以以下列出。我們先來寫那個檢測毛病的謂詞。
(define (symbol-in-tree? gven-symbol tree)
(not (false? (find (lambda (s) (eq? s given-symbol))
(symbols tree)))))
(define (encode-symbol symbol tree)
(cond ((leaf? tree) ‘())
((symbol-in-tree? symbol (left-branch tree))
(cons 0 (encode-symbol symbol (left-branch tree))))
((symbol-in-tree? symbol (right-branch tree))
(cons 1 (encode-symbol symbol (right-branch tree))))
(else
(error “Error: symbol not in this tree!”))))
如此1來即可以得出encode了。
(define (encode message tree)
(if (null? message)
‘()
(append (encode-symbol (car message) tree)
(encode (cdr message) tree))))
通過測試我們發現和上1題中的結果完全符合,如前面所說要導入sample-tree。
(encode ‘( a d a b b c a) sample-tree)
;Value: (0 1 1 0 0 1 0 1 0 1 1 1 0)
上一篇 Js 冒泡事件阻止