-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise2-71.lisp
95 lines (87 loc) · 2.68 KB
/
exercise2-71.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
(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))
(caddr tree)))
(define (weight tree)
(if (leaf? tree)
(weight-leaf tree)
(cadddr tree)))
(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))))
(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))))))
(define (make-leaf-set pairs)
(if (null? pairs)
'()
(let ((pair (car pairs)))
(adjoin-set (make-leaf (car pair) ; symbol
(cadr pair)) ; frequency
(make-leaf-set (cdr pairs))))))
(define (encode-symbol letter tree)
(if (leaf? tree)
'()
(if (memq letter (symbols (left-branch tree)))
(cons 0 (encode-symbol letter (left-branch tree)))
(cons 1 (encode-symbol letter (right-branch tree))))))
(define (encode message tree)
(if (null? message)
'()
(append (encode-symbol (car message) tree)
(encode (cdr message) tree))))
(define (successive-merge set)
(if (= 1 (length set))
(first set)
(let ((merged (make-code-tree (first set) (second set)))
(rest (cddr set)))
(successive-merge (adjoin-set merged rest)))))
(define (generate-huffman-tree pairs)
(successive-merge (make-leaf-set pairs)))
(define pairs
(list '(a 1)
'(b 2)
'(c 4)
'(d 8)
'(e 16)))
(define tree (generate-huffman-tree pairs))
(map (lambda (x) (encode-symbol x tree)) '(a b c d e))
(define pairs
(list '(a 1)
'(b 2)
'(c 4)
'(d 8)
'(e 16)
'(f 32)
'(g 64)
'(h 128)
'(i 256)
'(j 512)))
(define tree (generate-huffman-tree pairs))
(map (lambda (x) (encode-symbol x tree)) '(a b c d e f g h i j))