lab8 - (define(withdraw amount(SET TRANSACTIONS(APPEND...

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

View Full Document Right Arrow Icon
CS 61A -- Week 8 solutions LAB ACTIVITIES: 1. Use a LET to keep both initial and current balance (define (make-account init-amount) (let ((BALANCE INIT-AMOUNT)) ;;; This is the change. (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) ;; two lines added here ((EQ? MSG 'INIT-BALANCE) INIT-AMOUNT))) dispatch)) 3. Add transaction history. (define (make-account init-amount) (let ((balance init-amount) (TRANSACTIONS '())) ;; add local state var
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
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: (define (withdraw amount) (SET! TRANSACTIONS (APPEND TRANSACTIONS (LIST (LIST 'WITHDRAW AMOUNT)))) ;; update (set! balance (- balance amount)) balance) (define (deposit amount) (SET! TRANSACTIONS (APPEND TRANSACTIONS (LIST (LIST 'DEPOSIT AMOUNT)))) ;; update (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) ((EQ? MSG 'TRANSACTIONS) TRANSACTIONS))) ;; message to examine it dispatch)) 4. Why substitution doesn't work. (plus1 5) becomes (set! 5 (+ 5 1)) 5 The first line (the SET!) is syntactically wrong; "5" isn't a variable 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; it ignores the fact that the SET! was supposed to change the result....
View Full Document

This note was uploaded on 05/12/2010 for the course CS 61A taught by Professor Harvey during the Spring '08 term at Berkeley.

Page1 / 2

lab8 - (define(withdraw amount(SET TRANSACTIONS(APPEND...

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

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