From 3d832af911d96731cc669fdcedbe5134841ea9ed Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Fri, 16 Apr 2021 19:23:29 -0400 Subject: [PATCH] Answer 5.33 --- ex-5_31-xx.scm | 56 +++++++++++++++++++++++++++++++++++--------------- 1 file changed, 40 insertions(+), 16 deletions(-) diff --git a/ex-5_31-xx.scm b/ex-5_31-xx.scm index 06160e4..39d4191 100644 --- a/ex-5_31-xx.scm +++ b/ex-5_31-xx.scm @@ -66,6 +66,7 @@ ev-appl-did-operator-no-restore (display "\nex-5.33 - compare-factorial-definitions\n") (define (compile-to-file code target linkage file-name) + (set! label-counter 0) (define (write-list-to-port xs port) (if (null? xs) '() @@ -85,22 +86,22 @@ ev-appl-did-operator-no-restore ; Uncomment the following lines to write the assembly code for the to methods ; into files. -;(compile-to-file -; '(define (factorial n) -; (if (= n 1) -; 1 -; (* (factorial (- n 1)) n))) -; 'val 'next "factorial.sicp-asm") -; -;; reset label counter to the same labels for diff +(compile-to-file + '(define (factorial n) + (if (= n 1) + 1 + (* (factorial (- n 1)) n))) + 'val 'next "factorial.sicp-asm") + +;(define label-counter 0) + +(compile-to-file + '(define (factorial-alt n) + (if (= n 1) + 1 + (* n (factorial-alt (- n 1))))) + 'val 'next "factorial-alt.sicp-asm") ;(define label-counter 0) -; -;(compile-to-file -; '(define (factorial-alt n) -; (if (= n 1) -; 1 -; (* n (factorial-alt (- n 1))))) -; 'val 'next "factorial-alt.sicp-asm") ; $ diff factorial.sicp-asm factorial-alt.sicp-asm ; 33,36c33,34 @@ -117,8 +118,31 @@ ev-appl-did-operator-no-restore ; > (restore env) ; > (assign val (op lookup-variable-value) (const n) (reg env)) +; The regular factorial needs an additional save-and-restore for argl before +; the recursive call. Argl must be saved because it contains the value of n +; before the recursive call. + +; The alternative factorial needs an additional save-and-restore for env before +; the recursive call. Env must be saved for other the evaluation of the +; remaining arguments. In this case, the look-up of n which comes second for +; the alternative implementation. + +; Neither version executes more efficiently and they have the same number of +; instructions. + +(display "[answered]\n") + +(display "\nex-5.34 - factorial-iter\n") +(compile-to-file + '(define (factorial n) + (define (iter product counter) + (if (> counter n) + product + (iter (* counter product) + (+ counter 1)))) + (iter 1 1)) + 'val 'next "factorial-iter.sicp-asm") -(display "\nex-5.34\n") (display "\nex-5.35\n")