lab9 - (set! balance (- balance amount)) balance) (define...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
Sheet1 Page 1 CS 61A -- Week 9 solutions LAB ACTIVITIES: 1. Use a LET to keep both initial and current balance (define (make-account init-amount) (let ((BALANCE INIT-AMOUNT)) (define (withdraw amount) (set! balance (- balance amount)) balance) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (dispatch msg) (cond ((eq? msg 'withdraw) withdraw) ((eq? msg 'deposit) deposit))) dispatch)) 2. Add messages to read those variables. (define (make-account init-amount) (let ((balance init-amount)) (define (withdraw amount) (set! balance (- balance amount)) balance) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (dispatch msg) (cond ((eq? msg 'withdraw) withdraw) ((eq? msg 'deposit) deposit) ((EQ? MSG 'BALANCE) BALANCE) ((EQ? MSG 'INIT-BALANCE) INIT-AMOUNT))) dispatch)) 3. Add transaction history. (define (make-account init-amount) (let ((balance init-amount) (TRANSACTIONS '())) (define (withdraw amount) (SET! TRANSACTIONS (APPEND TRANSACTIONS (LIST (LIST 'WITHDRAW AMOUNT))))
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 4
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: (set! balance (- balance amount)) balance) (define (deposit amount) (SET! TRANSACTIONS (APPEND TRANSACTIONS (LIST (LIST 'DEPOSIT AMOUNT)))) (set! balance (+ balance amount)) balance) (define (dispatch msg) (cond ((eq? msg 'withdraw) withdraw) Sheet1 Page 2 ((eq? msg 'deposit) deposit) ((eq? msg 'balance) balance) ((eq? msg 'init-balance) init-amount) ((EQ? MSG 'TRANSACTIONS) TRANSACTIONS))) dispatch)) 4. Why substitution doesn't work. (plus1 5) becomes (set! 5 (+ 5 1)) 5 The first line (the SET!) is syntactically wrong and it doesn't make sense to substitute into an unevaluated part of a special form. The second line (returning the value 5) is syntactically okay but gives the wrong answer to change the result. Sheet1 Page 3 This is the change. two lines added here add local state var update update Sheet1 Page 4 message to examine it "5" isn't a variable it ignores the fact that the SET! was supposed...
View Full Document

This note was uploaded on 09/14/2009 for the course PEIS 100 taught by Professor Mckenzie during the Spring '08 term at University of California, Berkeley.

Page1 / 4

lab9 - (set! balance (- balance amount)) balance) (define...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online