연습문제 3.1 ~ 3.4

0 views
Skip to first unread message
Message has been deleted

M.TVLLI.CICERO

unread,
Jan 30, 2008, 1:56:36 AM1/30/08
to sicp-sig
;;; 3.1
(define (make-accumulator value)
(lambda (n)
(begin
(set! value (+ value n))
value)))

(define A (make-accumulator 5))

(A 10)

(A 10)

;; 3.2
(define (make-monitored f)
(let ((rc 0))
(lambda (m)
(cond ((eq? m 'reset-count) (set! rc 0))
((eq? m 'how-many-calls?) rc)
(else (begin (set! rc (+ 1 rc)) (f m)))))))

(define s (make-monitored sqrt))

(s 100)
(s 65536)
(s 'how-many-calls?)
(s 4294967296)
(s 'how-many-calls?)

;; 3.3 & 3.4
(define (make-account password balance)
(let ((incorrect-count 0))
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount))
balance)
(define (call-the-cops)
"Call the cops!")
(define (incorrect-password amount)
(begin (set! incorrect-count (+ incorrect-count 1))
(if (> incorrect-count 7)
(call-the-cops)
"Incorrect password")))
(define (dispatch p m)
(if(eq? p password)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request -- MAKE-ACCOUNT"
m)))
incorrect-password))
dispatch))

(define acc (make-account 'break 100))
((acc 'break 'withdraw) 50)
((acc 'lock 'withdraw) 60)
((acc 'break 'deposit) 40)
((acc 'break 'withdraw) 60)
((acc 'lock 'withdraw) 1000)
((acc 'lock 'withdraw) 1000)
((acc 'lock 'withdraw) 1000)
((acc 'lock 'withdraw) 1000)
((acc 'lock 'withdraw) 1000)
((acc 'lock 'withdraw) 1000)
((acc 'lock 'withdraw) 1000)
((acc 'lock 'withdraw) 1000)
((acc 'lock 'withdraw) 1000)

Reply all
Reply to author
Forward
0 new messages