exercises.org 1.4 KB

CHAPTER 3

Exercise 3.1

  (define (make-accumulator start)
    (lambda (add) (begin (set! start (+ start add))
			 start)))
  (define A (make-accumulator 3))
  (A 10)

Exercise 3.2

  (define (sqrt x) (* x x))
  (define (make-monitored f)
    (let ((calls 0))
      (define (mf input)
	(cond ((eq? input 'how-many-calls?)
	       calls)
	      ((eq? input 'reset-count)
	       (begin (set! calls 0)
		      calls))
	      (else (begin (set! calls (+ 1 calls))
			   (f input)))))
      mf))
  (define ctsqrt (make-monitored sqrt))
  (ctsqrt 100)
  (ctsqrt 1000)
  (ctsqrt 10000)
  (ctsqrt 'how-many-calls?)

Exercise 3.3

  (define (make-account balance password)
    (let ((pw 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 m password)
	(cond ((not (eq? password pw))
	       (error "wrong password"))
	      ((eq? m 'withdraw) withdraw)
	      ((eq? m 'deposit) deposit)
	      (else (error "Unknown request -- MAKE-ACCOUNT"
			   m))))
      dispatch))

  (define acc (make-account 100 'opensesame))
  ((acc 'deposit 'opensesame) 20)

  ;;(define (make-joint acct password new-pass)