commit 11a5759d3ad293cc2e38127888edf5d1e2db503e
parent 660a9ffb718ce541994fb28d2949350d0a1ae952
Author: Yuval Langer <yuval.langer@gmail.com>
Date: Mon, 27 Mar 2023 14:01:08 +0300
Add some chapter 2.3 Symbolic Data solutions and tests.
Diffstat:
3 files changed, 35 insertions(+), 9 deletions(-)
diff --git a/solutions/huffman-codes-stuff.scm b/solutions/huffman-codes-stuff.scm
@@ -1,7 +1,12 @@
(define-library (huffman-codes-stuff)
(import (scheme base))
(import (scheme cxr))
-
+ (export make-code-tree
+ make-leaf
+ sample-message
+ sample-tree
+ generate-huffman-tree)
+
(begin
(define (make-leaf symbol weight)
(list 'leaf symbol weight))
@@ -58,7 +63,7 @@
(cond
((null? set) (list x))
((< (weight x)
- (car set))
+ (weight (car set)))
(cons x set))
(else (cons (car set)
(adjoin-set x
@@ -74,7 +79,7 @@
(make-leaf-set (cdr pairs))))))
;; Exercise 2.67
-
+
(define sample-tree
(make-code-tree
(make-leaf 'A 4)
@@ -86,7 +91,7 @@
(define sample-message
'(0 1 1 0 0 1 0 1 0 1 1 1 0))
-
+
;; Exercise 2.68
@@ -109,7 +114,7 @@
(encode-symbol' (cons 1 bits)
(right-branch current-tree)))
(else (error "Symbol is unknown: " symbol))))
-
+
(reverse (encode-symbol' '() tree)))
(define (encode message tree)
@@ -127,11 +132,12 @@
((null? leaf-set) '())
((null? (cdr leaf-set))
(car leaf-set))
- (else (make-code-tree (car leaf-set)
- (successive-merge' (cdr leaf-set))))))
-
+ (else (make-code-tree
+ (car leaf-set)
+ (successive-merge'
+ (cdr leaf-set))))))
(successive-merge' (reverse leaf-set)))
-
+
(define (generate-huffman-tree pairs)
(successive-merge
(make-leaf-set pairs)))))
diff --git a/solutions/tests/exercise-2.67-tests.scm b/solutions/tests/exercise-2.67-tests.scm
@@ -1,3 +1,6 @@
+(import (srfi :64))
+(import (huffman-codes-stuff))
+
(test-begin "2.67")
(test-equal
'(A D A B B C A) ;; Is this it? Did I fuck any shit up? Manuel de Coding, the Portuguese decoder, agrees with this.
diff --git a/solutions/tests/exercise-2.69-tests.scm b/solutions/tests/exercise-2.69-tests.scm
@@ -1,4 +1,15 @@
(import (srfi :64))
+(import (huffman-codes-stuff))
+
+'(make-code-tree
+ (make-code-tree (make-leaf 'A 1)
+ (make-leaf 'B 1))
+ (make-code-tree (make-leaf 'C 1)
+ (make-leaf 'D 1)))
+'(((leaf A 1) (leaf B 1) (A B) 2)
+ ((leaf C 1) (leaf D 1) (C D) 2)
+ (A B C D)
+ 4)
(test-begin "2.69")
(test-equal
@@ -8,4 +19,10 @@
(make-code-tree (make-leaf 'A 1)
(make-leaf 'B 1))
(generate-huffman-tree '((A 1) (B 1))))
+(test-equal
+ sample-tree
+ (generate-huffman-tree '((D 1)
+ (C 1)
+ (B 2)
+ (A 4))))
(test-end "2.69")