我的一个长期项目是完成 SICP 的所有练习。我注意到最近的练习有点奇怪。我正在测试一个霍夫曼编码树。当我在 DrScheme 中执行以下代码时,我得到了预期的结果:
(a d a b b c a)
但是,如果我通过调用 (load "2.67.scm") 或运行 mzscheme -f 2.67.scm 在 mzscheme 中执行相同的代码,它会报告:
symbols: expected symbols as arguments, given: (leaf D 1)
我的问题是:为什么?是不是因为 mzscheme 和 drscheme 使用不同的规则来加载程序定义?程序代码如下。
;; Define an encoding tree and a sample message
;; Use the decode procedure to decode the message, and give the result.
(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 (test s-exp)
(display s-exp)
(newline))
(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)))))
(define sample-message '(0 1 1 0 0 1 0 1 0 1 1 1 0))
(test (decode sample-message sample-tree))