Saturday, May 28, 2011

Solution of SICP Exercise 5.14

Below is the solution of Exercise 5.14.
Found some solutions on the web try to get
the trace information using something like
((factorial-machine 'stack) print-statistics)
instead of modifying instructions set of the factorial machine,
which is not the intent of this exercise.

下面是练习5.14的解决方案。
我注意到有些网上的方案直接访问STACK的print-statistics函数。
((factorial-machine 'stack) print-statistics)
显然这不是本练习的目的。

練習問題5.14の回答は下記の通りになります。
直接スタックのprint-statistics関数を使用し、
情報を取得することも可能ですが、本練習の目的ではないと思います。

(define fm
  (make-machine
  '(n val continue)
  (list (list '= =) (list '- -) (list '* *) (list 'read read) (list 'output write))
  '(controller
    (assign n (op read))
    (perform (op initialize-stack))
    (assign continue (label fact-done))
 fact-loop
    (test (op =) (reg n) (const 1))
    (branch (label base-case))
    (save continue)
    (save n)
    (assign n (op -) (reg n) (const 1))
    (assign continue (label after-fact))
    (goto (label fact-loop))
 after-fact
    (restore n)
    (restore continue)
    (assign val (op *) (reg n) (reg val))
    (goto (reg continue))
 base-case
    (assign val (const 1))
    (goto (reg continue))
 fact-done
    (perform (op output) (reg val))
    (perform (op print-stack-statistics))
    (goto (label controller)))))

No comments:

Post a Comment