diff options
| author | Mike Vink <mike1994vink@gmail.com> | 2023-05-12 23:10:43 +0200 |
|---|---|---|
| committer | Mike Vink <mike1994vink@gmail.com> | 2023-05-12 23:10:43 +0200 |
| commit | 47d68a308febd22174aae26c82fa3b1b5088a866 (patch) | |
| tree | 5250afce79d14a38c65a37ef4d3b5402efdf0402 | |
| parent | ff68a95c6cac90d511290265b2e6c1dde1c0278a (diff) | |
start chapter 3
| -rw-r--r-- | coding-exercises/3/1.rkt | 71 | ||||
| -rw-r--r-- | coding-exercises/3/5.rkt | 0 |
2 files changed, 71 insertions, 0 deletions
diff --git a/coding-exercises/3/1.rkt b/coding-exercises/3/1.rkt new file mode 100644 index 0000000..4299e9d --- /dev/null +++ b/coding-exercises/3/1.rkt @@ -0,0 +1,71 @@ +#lang racket +;; 1 +(define (make-accumulator amount) + (lambda (add-this) + (set! amount (+ amount add-this)) + amount)) +(define A (make-accumulator 5)) +(A 10) +(A 15) + +(define B (make-accumulator 5)) +(B 10) +(B 15) + +;; 2 +(define (make-monitored fn) + (define calls (make-accumulator 0)) + (lambda (arg-or-message) + (cond ((equal? arg-or-message 'how-many-calls?) (calls 0)) + ((equal? arg-or-message 'reset-count) (set! calls (make-accumulator 0))) + (else (begin + (calls 1) + (fn arg-or-message)))))) +(define s (make-monitored sqrt)) +(s 100) +(s 'how-many-calls?) + +;; 3 +(define (make-account balance secret) + (define (withdraw amount) + (if (>= balance amount) + (begin (set! balance (- balance amount)) balance) + "Insufficient funds")) + (define (deposit amount) + (set! balance (+ balance amount)) + balance) + (define (dispatch m) + (cond ((eq? m 'withdraw) withdraw) + ((eq? m 'deposit) deposit) + (else (error "Unknown request -- MAKE-ACCOUNT" m)))) + + (define (args->dispatch fn) + (lambda (arg-list) + (let ((password (car arg-list)) + (m (cadr arg-list))) + (if (eq? password secret) + (fn m) + (lambda (a . n) + "Wrong password"))))) + + (define monitored-dispatch (make-monitored (args->dispatch dispatch))) + (define (call-the-cops) + (lambda (a . n) + "Calling the cops")) + + (define (safe-dispatch . args) + (if (> 7 (monitored-dispatch 'how-many-calls?)) + (monitored-dispatch args) + (call-the-cops))) + safe-dispatch) + +(define acc (make-account 100 'secret-password)) +((acc 'secret-password 'withdraw) 10) +((acc 'some-other-password 'deposit) 50) +((acc 'some-other-password 'deposit) 50) +((acc 'some-other-password 'deposit) 50) +((acc 'some-other-password 'deposit) 50) +((acc 'some-other-password 'deposit) 50) +((acc 'some-other-password 'deposit) 50) +((acc 'some-other-password 'deposit) 50) +((acc 'some-other-password 'deposit) 50) diff --git a/coding-exercises/3/5.rkt b/coding-exercises/3/5.rkt new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/coding-exercises/3/5.rkt |
