灯下 登录
计算机科学 / SICP / 2.3.4 Example: Huffman Encoding Trees

Exercise 2.68 · 习题

Exercise 2.68: The encode procedure takes
as arguments a message and a tree and produces the list of bits that gives the
encoded message.

(define (encode message tree)
(if (null? message)
'()
(append
(encode-symbol (car message)
tree)
(encode (cdr message) tree))))

Encode-symbol is a procedure, which you must write, that returns the

list of bits that encodes a given symbol according to a given tree. You should

design encode-symbol so that it signals an error if the symbol is not in

the tree at all. Test your procedure by encoding the result you obtained in

Exercise 2.67 with the sample tree and seeing whether it is the same as

the original sample message.

练习 2.68:encode 过程以消息和树为参数,产生给出编码消息的比特表。

(define (encode message tree)
(if (null? message)
'()
(append
(encode-symbol (car message)
tree)
(encode (cdr message) tree))))

encode-symbol 是一个你必须编写的过程,它根据给定的树返回对给定符号编码的比特表。你应当将 encode-symbol 设计为:若符号不在树中,则发出错误信号。通过将练习 2.67 中得到的结果用样本树编码,验证你的过程是否与原始的样本消息相同,以此测试你的过程。

Racket #lang sicp
(define (encode message tree)
 (if (null? message)
 '()
 (append
 (encode-symbol (car message)
 tree)
 (encode (cdr message) tree))))