問題5.48 – SICP(計算機プログラムの構造と解釈)その300
2009年12月29日
問題5.48
;; 環境に compile-and-run を基本手続として追加する。 (define (setup-environment2) (extend-environment (list 'compile-and-run) (list (list 'primitive compile-and-run)) (setup-environment))) ;; setup-environment2 を呼び出すように変更する。 (define (compile-and-go expression) (let ((instructions (assemble (statements (compile expression 'val 'return)) eceval))) (set! the-global-environment (setup-environment2)) (set-register-contents! eceval 'val instructions) (set-register-contents! eceval 'flag true) (start eceval))) (define (compile-and-run? proc) (tagged-list? proc 'compile-and-run)) (define (compile-and-run expression) (let ((instructions (assemble (statements (compile expression 'val 'return)) eceval))) (set-register-contents! eceval 'val instructions) (set-register-contents! eceval 'flag true) (start eceval))) (define eceval-operations (list (list 'self-evaluating? self-evaluating?) ;; 省略 (list 'compile-and-run? compile-and-run?) (list 'compile-and-run compile-and-run) ;; 省略 )) (define eceval ;; 省略 ev-compile-and-run (perform (op compile-and-run) (reg exp)) (goto (reg continue)) ;; 省略 )))
翻訳した Factorial 手続き(factorial)と合成手続きの Factorial (factorial2) での total-pushes と max-depth を比較すると、積極制御評価器上で compile-and-run 手続きを使って翻訳できていることがわかる。
$ gosh
gosh> (load "./ece4compiler.scm")
#t
gosh> (compile-and-go
'(define (square x) (* x x)))
(total-pushes = 0 max-depth = 0)
;;; EC-Eval value:
ok
;;; EC-Eval input:
(square 4)
(total-pushes = 5 max-depth = 3)
;;; EC-Eval value:
16
;;; EC-Eval input:
(compile-and-run
'(define (factorial n)
(if (= n 1)
1
(* (factorial (- n 1)) n))))
(total-pushes = 0 max-depth = 0)
;;; EC-Eval value:
ok
;;; EC-Eval input:
(factorial 5) ; <= 翻訳した Factorial
(total-pushes = 31 max-depth = 14)
;;; EC-Eval value:
120
;;; EC-Eval input:
(define (factorial2 n)
(if (= n 1)
1
(* (factorial2 (- n 1)) n)))
(total-pushes = 3 max-depth = 3)
;;; EC-Eval value:
ok
;;; EC-Eval input:
(factorial2 5) ; <= 合成手続き(解釈された手続き)の Factorial
(total-pushes = 144 max-depth = 28)
;;; EC-Eval value:
120
計算機プログラムの構造と解釈
posted with amazlet at 08.11.07
ジェラルド・ジェイ サスマン ジュリー サスマン ハロルド エイブルソン
ピアソンエデュケーション
売り上げランキング: 6542
ピアソンエデュケーション
売り上げランキング: 6542
