SICP 全笔记

Exercise 5.8. The following register-machine code is ambiguous, because the label here is defined more than once:

start
  (goto (label here))
here
  (assign a (const 3))
  (goto (label there))
here
  (assign a (const 4))
  (goto (label there))
there

With the simulator as written, what will the contents of register a be when control reaches there? Modify the extract-labels procedure so that the assembler will signal an error if the same label name is used to indicate two different locations.

根据之前的分析, extract-labels 将会返回 labels 和 instructions 的 list。

lookup-labels 使用 assoc 来获取某个 labels 的对应。 assoc 的实现只找第一个符合条件的值,所以这里的 a 中将保存 3。

新的 extract-labels 如下:

(load "machine-assemble-module.scm")

(define (extract-labels text receive)
  (if (null? text)
      (receive '() '())
      (extract-labels
       (cdr text)
       (lambda (labels insts)
         (let ((next-inst (car text)))
           (cond ((and (symbol? next-inst) (assoc next-inst labels))
                  (error 'extract-labels "Duplicate labels: " next-inst))
                 ((symbol? next-inst)
                  (receive
                      (cons (make-label-entry next-inst insts) labels)
                      insts))
                 (else 
                  (receive
                      labels
                      (cons (make-instruction next-inst) insts)))))))))
(let ((text
       '(start
         (goto (label here))
         here
         (assign a (const 3))
         (goto (label there))
         here
         (assign a (const 4))
         (goto (label there))
         there)))
  (assert/exn
   (extract-labels text (lambda (labels insts) labels))
   "Duplicate"))