2015/10/27

# SICP 問題 2.67

``````;; Huffman木

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

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

(define (symbol-leaf x) (cadr x))

(define (weight-leaf x) (caddr x))

(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) (cadr tree))

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

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

;; bitが0なら左，1なら右の枝をたどっていき，leafにたどり着くと，そのシンボルをconsして次にいく．
(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))

;; bitが左ならleft-branch,bitが右ならright-branchを選択
(define (choose-branch bit branch)
(cond ((= bit 0) (left-branch branch))
((= bit 1) (right-branch branch))
(else (error "bad bit -- CHOOSE-BRANCH" bit))))

;; weightで昇順に順序づけられた集合に要素を追加する
(define (adjoin-set x set)
(cond ((null? set) (list x))
((< (weight x) (weight (car set))) (cons x set))
(else (cons (car set)
(adjoin-set x (cdr set))))))

;; pairsからweightの昇順にleafの集合を作る．
(define (make-leaf-set pairs)
(if (null? pairs)
'()
(let ((pair (car pairs)))
(adjoin-set (make-leaf (car pair)
(make-leaf-set (cdr pairs))))))
``````
``````gosh> (define sample-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)))))
sample-tree
gosh> (define sample-message
'(0 1 1 0 0 1 0 1 0 1 1 1 0))
sample-message
gosh> (decode sample-message sample-tree)
(A D A B B C A)``````