(wat-aro)

無職から有職者にランクアップしました

SICP 問題 5.04

;; a 再帰的べき乗
(define (expt b n)
  (if (= n 0)
      1
      (* b (expt b (- n 1)))))
(controller
   (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)

 
 

;; b 反復的べき乗
(define (expt b n)
  (define (expt-iter counter product)
    (if (= counter 0)
        product
        (expt-iter (- counter 1) (* product))))
  (expt-iter n 1))
(contoroller
   (assign product (const 1))
 expt-loop
   (test (op =) (reg n) (const 0))
   (branch (label fib-done))
   (assign n1 (op -) (reg n) (const 1))
   (assign p1 (op *) (reg product) (reg b))
   (assign n (reg n1))
   (assigin product (reg p1))
   (goto (label expt-loop))
 expt-done)