Answer 5.33

This commit is contained in:
2021-04-16 19:23:29 -04:00
parent ba682d8f6a
commit 3d832af911

View File

@@ -66,6 +66,7 @@ ev-appl-did-operator-no-restore
(display "\nex-5.33 - compare-factorial-definitions\n") (display "\nex-5.33 - compare-factorial-definitions\n")
(define (compile-to-file code target linkage file-name) (define (compile-to-file code target linkage file-name)
(set! label-counter 0)
(define (write-list-to-port xs port) (define (write-list-to-port xs port)
(if (null? xs) (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 ; Uncomment the following lines to write the assembly code for the to methods
; into files. ; into files.
;(compile-to-file (compile-to-file
; '(define (factorial n) '(define (factorial n)
; (if (= n 1) (if (= n 1)
; 1 1
; (* (factorial (- n 1)) n))) (* (factorial (- n 1)) n)))
; 'val 'next "factorial.sicp-asm") 'val 'next "factorial.sicp-asm")
;
;; reset label counter to the same labels for diff ;(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) ;(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 ; $ diff factorial.sicp-asm factorial-alt.sicp-asm
; 33,36c33,34 ; 33,36c33,34
@@ -117,8 +118,31 @@ ev-appl-did-operator-no-restore
; > (restore env) ; > (restore env)
; > (assign val (op lookup-variable-value) (const n) (reg 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") (display "\nex-5.35\n")