diff --git a/ex-3_01-xx.scm b/ex-3_01-xx.scm new file mode 100644 index 0000000..ac5c349 --- /dev/null +++ b/ex-3_01-xx.scm @@ -0,0 +1,82 @@ +(load "util.scm") + +(display "\nex-3.1\n") + +(define (make-accumulator value) + (define (accumulate new-value) + (set! value (+ value new-value)) + value) + accumulate) + +(define A (make-accumulator 5)) +(assert (A 10) 15) +(assert (A 10) 25) + +(display "\nex-3.2\n") + +(define (make-monitored proc) + (define count 0) + (define (dispatch m) + (cond ((eq? m 'how-many-calls?) count) + ((eq? m 'reset-count) (set! count 0) count) + (else (set! count (inc count)) + (proc m)))) + dispatch) + +(define s (make-monitored sqrt)) + +(assert (s 100) 10) +(assert (s 9) 3) +(assert (s 'how-many-calls?) 2) +(s 'reset-count) +(assert (s 'how-many-calls?) 0) + + +(display "\nex-3.3\n") + +(define (make-account balance password) + (define invalid-pw-attempts 0) + (define (withdraw amount) + (if (>= balance amount) + (begin (set! balance (- balance amount)) + balance) + "Insufficient funds")) + (define (deposit amount) + (set! balance (+ balance amount)) + balance) + (define (incorrect-password value) + "Incorrect password") + (define (call-the-cops value) + "Call the cops!") + (define (dispatch pw m) + (if (eq? pw password) + (begin + (set! invalid-pw-attempts 0) + (cond + ((eq? m 'withdraw) withdraw) + ((eq? m 'deposit) deposit) + (else (error "Unknown request -- MAKE-ACCOUNT" m)))) + (cond + ((= invalid-pw-attempts 3) call-the-cops) + (else + (set! invalid-pw-attempts (inc invalid-pw-attempts)) + incorrect-password)))) + dispatch) + +(define acc (make-account 100 'secret-password)) + +(assert ((acc 'secret-password 'withdraw) 40) 60) +(assert ((acc 'some-other-password 'deposit) 50) "Incorrect password") + +(display "\nex-3.4\n") + +((acc 'some-other-password 'deposit) 50) +(assert ((acc 'secret-password 'deposit) 50) 110) +((acc 'some-other-password 'deposit) 50) +((acc 'some-other-password 'deposit) 50) +((acc 'some-other-password 'deposit) 50) +(assert ((acc 'some-other-password 'deposit) 50) "Call the cops!") + + +(display "\nex-3.5\n") +