6. Objects with local storage
- Look at my posted example of local storage at different levels of procedure definition. Try to predict the results of applications of
p1a and p2a before looking at the evaluations.
- Redefine
make-account (page 223 of the text) so that it uses an explicit let or define to introduce local storage for the balance of an account, instead of depending on the preservation of the storage associated with the balance parameter. (I discuss this point a bit more at the end of this note.)
- Define a variation on
make-account. The text uses a message-passing form, where a single procedure returned by (make-account balance) takes arguments withdraw and deposit to determine its action. Instead of that, let your variant make-account return a pair of procedures, one to perform a withdrawal, the other to perform a deposit. Figure out how to use your variant make-account to define separate procedures withdraw-acct1 and deposit-acct1 that operate on the same local storage.
- Define a second variation on
make-account, called make-account-database, to create a single object representing all accounts at a (very small) bank, in the form of a list of pairs of account number and balance. Define procedures withdraw and deposit that take an account number as argument and modify the appropriate entries in the database list.
- Define an instrumented
sum procedure, that keeps track of the sum of the lengths of all lists that it has been applied to.
Go over the meanings of define, let, and set! carefully. You may do this by studying Chapter 3 in the text, but I find the concise definitions in the MIT Scheme Reference Manual handier. Make sure that you understand the distinction between binding and assignment, and which combination of binding and assignment is performed by each of define, let, and set!. To provide backwards compatibility with older Lisps, and to make certain common combinations of binding and assignment convenient, Scheme overlaps the behavior of these procedures a bit, so that certain bindings/assignments may be achieved by more than one form in a program.
In addition to variables introduced by define, parameters to procedures may also be used as local storage in Scheme, as in the make-withdraw and make-account examples on pages 222 and 223 of the text. This use of parameters as local storage is peculiar to Scheme, and does not necessarily work the same way in other programming languages. I have not used that technicque in the exam, and I suggest that you ignore it, other than seeing how to replace it by an explicit use of let or define.
|