CS 22
Clab 16: State and assignment
I'll say a word or two about state and then we'll look at some of the
section 3.1.1 code together.
http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-20.html#%_sec_3.1
(define (make-withdraw balance)
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds")))
Put this in a drscheme window and try.
> (define amy (make-withdraw 70))
> (define matt (make-withdraw 40))
> matt
#
> amy
#
> (amy 50)
20
> (matt 50)
"Insufficient funds"
> (matt 25)
15
> (amy 0)
20
> (matt 0)
15
> (amy -100)
120
You can see that these accounts are procedures with local 'state'.
Matt's account is different from Amy's and each account keeps track
of its own balance. We change state by using the assignment operator:
"set!". It is a bit wierd to have to make deposits by
entering a negative amount and using 0 to find balance is also strange.
So let's improve these a bit.
(define (make-account balance)
(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)
((eq? m 'balance) balance)
(else (error "Unknown request -- MAKE-ACCOUNT"
m))))
dispatch)
Now try:
> (define alex (make-account 400))
> (define mal (make-account 125))
> alex
#
> (alex 'balance)
400
> ((alex 'withdraw) 20)
380
> (alex 'balance)
380
> (mal 'balance)
125
>
> ((mal 'deposit) 230)
355
>
Again, an account is a procedure with local state. Each procedure keeps
its own private local state that does not interfere with any other accounts
local state.
Enough talk. It's time for
you to work and me to change from "sage on the stage" to
"guide on the side".
So now you code up solutions to ex 3.1 and 3.2 on page 224-5.
Show me your solution to 3.2
After you have finished those, code up a solution to ex 3.8 on
page 236. How can you test your answer? That is, how can you
be sure your f function does its job? Once you are sure that
your f function works, in what order does it appear that drscheme
evaluates the arguments to + ?
Ask any questions you may have.