Domanda

Un progetto a lungo termine che ho sta lavorando attraverso tutti gli esercizi di SICP. Ho notato qualcosa di un po 'strano con il più recente esercizio. Sto testando un albero di codifica di Huffman. Quando eseguire il seguente codice nel DrScheme ottengo il risultato atteso:

(a d a b b c a)

Tuttavia, se eseguo questo stesso codice in MzScheme chiamando (carico "2.67.scm") o eseguendo MzScheme -f 2.67.scm, riporta:

symbols: expected symbols as arguments, given: (leaf D 1) 

La mia domanda è: perché? È perché MzScheme e drscheme usano regole diverse per le definizioni di programmi di carico? Il codice del programma è inferiore.

;; 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))
È stato utile?

Soluzione

Per impostazione predefinita, MzScheme si avvia in una modalità in cui non v'è una definizione esistente per symbols, e inline funzioni che è a conoscenza - così quando si compila la tua definizione make-code-tree, utilizza il legame è a conoscenza. Quando successivamente compila il tuo symbols, non ha un effetto sulla definizione precedente.

Il modo più semplice per affrontare questo è quello di rendere il codice in un modulo, mettendo il prefisso con un #lang scheme.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top