SICP 全笔记

Exercise 5.9. The treatment of machine operations above permits them to operate on labels as well as on constants and the contents of registers. Modify the expression-processing procedures to enforce the condition that operations can be used only with registers and constants.

make-operation-exp 的问题在于,它无法检查在 assemble 的阶段检查出 (test (op =) (label label1) (const 1)) 的错误来。

我们可以这样来改进

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

(define (make-operation-exp exp machine labels operations)
  (let ((op (lookup-prim (operation-exp-op exp) operations))
        (aprocs
         (map (lambda (e)
                (cond ((label-exp? e)
                       (error 'make-operation-exp "Bad expression type " e))
                      (else
                       (make-primitive-exp e machine labels))))
              (operation-exp-operands exp))))
    ; apply the op to all operands
    (lambda ()
      (apply op (map (lambda (p) (p)) aprocs)))))


(load "../testframe.scm")
(assert/exn
  (make-machine '(n) (list (list '- -))
   '((assign n (op -) (label after-expt) (const 1))
     after-expt
     expt-done))
  "Bad expression")