問題5.7 – SICP(計算機プログラムの構造と解釈)その255

問題5.7

再帰的べき乗を計算する計算機

(define expt-machine
  (make-machine
    '(b n val continue)
    (list (list '= =) (list '* *) (list '- -))
    '((assign continue (label expt-done))
  expt-loop
    (test (op =) (reg n) (const 0))
    (branch (label base-case))
    (save continue)
    (save n)
    (assign n (op -) (reg n) (const 1))
    (assign continue (label after-expt))
    (goto (label expt-loop))
  after-expt
    (restore n)
    (restore continue)
    (assign val (op *) (reg b) (reg val))
    (goto (reg continue))
  base-case
    (assign val (const 1))
    (goto (reg continue))
  expt-done)))

実行結果

(set-register-contents! expt-machine 'b 2)
gosh> done
(set-register-contents! expt-machine 'n 8)
gosh> done
(start expt-machine)
gosh> done
(get-register-contents expt-machine 'val)
gosh> 256

反復的べき乗を計算する計算機

(define expt-machine
  (make-machine
    '(b n counter product)
    (list (list '= =) (list '* *) (list '- -))
    '((assign counter (reg n))
     (assign product (const 1))
  expt-loop
    (test (op =) (reg counter) (const 0))
    (branch (label expt-done))
    (assign counter (op -) (reg counter) (const 1))
    (assign product (op *) (reg b) (reg product))
    (goto (label expt-loop))
  expt-done)))

実行結果

(set-register-contents! expt-machine 'b 2)
gosh> done
(set-register-contents! expt-machine 'n 8)
gosh> done
(start expt-machine)
gosh> done
(get-register-contents expt-machine 'product)
gosh> 256
計算機プログラムの構造と解釈
ジェラルド・ジェイ サスマン ジュリー サスマン ハロルド エイブルソン
ピアソンエデュケーション
売り上げランキング: 6542
«
»