DrScheme与mzscheme:定义的处理

时间:2008-12-24 11:20:55

标签: scheme racket sicp

我有一个长期项目正在完成SICP的所有练习。我注意到最近的练习有些奇怪。我正在测试一个霍夫曼编码树。当我在DrScheme中执行以下代码时,我得到了预期的结果:

(a d a b b c a)

但是,如果我通过调用(加载“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))

1 个答案:

答案 0 :(得分:6)

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

处理此问题的最简单方法是将代码添加到模块中,方法是在其前面添加#lang scheme