# 练习 2.67¶

1 ]=> (load "p112-huffman.scm")

;Value: weight

;... done
;Value: choose-branch

1 ]=> (define tree (make-code-tree (make-leaf 'A 4)
(make-code-tree (make-leaf 'B 2)
(make-code-tree (make-leaf 'D 1)
(make-leaf 'C 1)))))

;Value: tree

1 ]=> (define msg '(0 1 1 0 0 1 0 1 0 1 1 1 0))

;Value: msg

1 ]=> (decode msg tree)

;Value 11: (a d a b b c a)


## 验证¶

[A B D C]
*
/ \
A   \
* [B D C]
/ \
B   \
* [D C]
/ \
D   C


[A B D C] 0 1 1 0 0 1 0 1 0 1 1 1 0
0 A 1 1 0 0 1 0 1 0 1 1 1 0 A
1 [B D C] 1 0 0 1 0 1 0 1 1 1 0 A
1 [D C] 0 0 1 0 1 0 1 1 1 0 A
0 D 0 1 0 1 0 1 1 1 0 AD
0 A 1 0 1 0 1 1 1 0 ADA
1 [B D C] 0 1 0 1 1 1 0 ADA
0 B 1 0 1 1 1 0 ADAB
1 [B D C] 0 1 1 1 0 ADAB
0 B 1 1 1 0 ADABB
1 [B D C] 1 1 0 ADABB
1 [D C] 1 0 ADABB

## 源码¶

;;; p112-huffman.scm

;; leaf
(define (make-leaf symbol weight)
(list 'leaf symbol weight))

(define (leaf? object)
(eq? (car object) 'leaf))

(define (symbol-leaf x)

(define (weight-leaf x)

;; tree

(define (make-code-tree left right)
(list left
right
(append (symbols left) (symbols right))
(+ (weight left) (weight right))))

(define (left-branch tree)
(car tree))

(define (right-branch tree)

(define (symbols tree)
(if (leaf? tree)
(list (symbol-leaf tree))

(define (weight tree)
(if (leaf? tree)
(weight-leaf tree)

;;; p113-decode.scm

(define (decode bits tree)
(define (decode-1 bits current-branch)
(if (null? bits)
'()
(let ((next-branch
(choose-branch (car bits) current-branch)))
(if (leaf? next-branch)
(cons (symbol-leaf next-branch)
(decode-1 (cdr bits) tree))
(decode-1 (cdr bits) next-branch)))))
(decode-1 bits tree))

(define (choose-branch bit branch)
(cond ((= bit 0)
(left-branch branch))
((= bit 1)
(right-branch branch))
(else
(error "bad bit -- CHOOSE-BRANCH" bit))))