sicp-3-1-1
Posted on 2015-02-25 20:47:35 +0900 in SICP
3.1
(define (make-accumulator initial)
(let ((accumulate initial))
(lambda (x)
(set! accumulate (+ accumulate x))
accumulate)))
3.2
(define (make-monitored proc)
(let ((call-times 0))
(define (dispatch m)
(cond
((eq? m 'how-many-calls?) call-times)
((eq? m 'reset-count) (set! call-count 0))
(else
(set! call-times (+ 1 call-times))
(proc m))))
dispatch))
3.3
(define (make-account balance password)
(define (withdraw amount)
(if (>= balance amount) (begin (set! balance (- balance amount)) balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount)) balance)
(define (dispatch pass m)
(if (not (eq? pass password))
(error "Bad password -- " pass)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request -- MAKE-ACCOUNT" m)))))
dispatch)
3.4
(define (make-account balance password)
(define (withdraw amount)
(if (>= balance amount) (begin (set! balance (- balance amount)) balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount)) balance)
(define (error-message amount)
(display 'incorrect-password))
(let ((incorrect-pass-count 0))
(define (dispatch pass m)
(if (not (eq? pass password))
(begin
(set! incorrect-pass-count (+ 1 incorrect-pass-count))
(if (> incorrect-pass-count 7)
call-the-cops
error-message))
(begin
(set! incorrect-pass-count 0)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request -- MAKE-ACCOUNT" m)))))))
dispatch)
Hide Comments
comments powered by Disqus