sicp-ex-3.3



<< Previous exercise (3.2) | Index | Next exercise (3.4) >>


Igor Saprykin

  
  
  
 (define (make-account balance password) 
   (define (withdraw amount) 
         (if (>= balance amount) 
                 (begin (set! balance (- balance amount)) 
                            balance) 
                 "Not enough money")) 
   (define (deposit amount) 
         (set! balance (+ balance amount)) 
         balance) 
   (define (dispatch pass m) 
         (if (not (eq? pass password)) 
                 (lambda (amount) "Wrong password") 
                 (cond ((eq? m 'withdraw) withdraw) 
                           ((eq? m 'deposit) deposit) 
                           (else (error "Unknown call -- MAKE-ACCOUNT" 
                                                    m))))) 
   dispatch) 
  
  
  
 ; An easier solution.  
  
 (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 p m) 
     (cond ((not (eq? p password)) (lambda (x) "Incorrect password")) 
           ((eq? m 'withdraw) withdraw) 
           ((eq? m 'deposit) deposit) 
           (else (error "Unknown request -- MAKE-ACCOUNT" m)))) 
   dispatch)