-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex2-69.scm
81 lines (60 loc) · 2.03 KB
/
ex2-69.scm
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
#lang scheme
(define true #t)
(define false #f)
(define (left-branch h-tree)
(car h-tree))
(define (right-branch h-tree)
(cadr h-tree))
(define (leaf? h-tree)
(eq? (car h-tree) 'leaf))
(define (symbols tree)
(if (leaf? tree)
(list (symbol-leaf tree))
(caddr tree)))
(define (symbol-leaf tree)
(cadr tree))
(define (make-code-tree left right)
(list left
right
(append (symbols left)
(symbols right))
(+ (weight left)
(weight right))))
(define (make-leaf symbol weight)
(list 'leaf symbol weight))
(define (weight tree)
(if (leaf? tree)
(leaf-weight tree)
(cadddr tree)))
(define (leaf-weight tree)
(caddr tree))
(define (generate-huffman-tree pairs)
(successive-merge (make-ordered-pairs pairs)))
(define (adjoin-to-set item set)
(cond ((null? set) (list item))
((equal? (car set) item) set)
((< (weight item) (weight (car set))) (cons item
set))
(else (cons (car set)
(adjoin-to-set item (cdr set))))))
(define (make-ordered-pairs pairs)
(if (null? pairs)
'()
(adjoin-to-set (car pairs)
(make-ordered-pairs (cdr pairs)))))
(define set (list '(leaf A 4) '(leaf B 3) '(leaf C 1) '(leaf D 2) '(leaf E 1)))
; First two item in the list will always be the ones with the least weights, so always merge them together.
(define (successive-merge ordered-pairs)
(if (null? (cdr ordered-pairs))
(car ordered-pairs)
(successive-merge (adjoin-to-set (make-code-tree (first ordered-pairs)
(second ordered-pairs))
(remaining ordered-pairs)))))
(define (first ordered-pairs)
(car ordered-pairs))
(define (second ordered-pairs)
(if (> (length ordered-pairs) 1)
(cadr ordered-pairs)
'()))
(define (remaining ordered-pairs)
(cddr ordered-pairs))