3

我的一个长期项目是完成 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))
4

1 回答 1

6

默认情况下,MzScheme 以存在 的现有定义的模式启动symbols,并且它内联它知道的函数——所以当它编译你的make-code-tree定义时,它使用它知道的绑定。当它稍后编译您的symbols时,它不会对先前的定义产生影响。

处理这个问题的最简单方法是把你的代码变成一个模块,在它前面加上一个#lang scheme.

于 2008-12-25T06:36:43.667 回答