gpt4 book ai didi

scheme - DrScheme 与 mzscheme : treatment of definitions

转载 作者:行者123 更新时间:2023-12-01 11:10:32 27 4
gpt4 key购买 nike

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

最佳答案

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

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

关于scheme - DrScheme 与 mzscheme : treatment of definitions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/391272/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com