Changing Data: (Continued) CMSC 11500 Introduction to Computer Programming November 4, 2002
Roadmap Recap: Assignment & Data with state Topical Example: Voting! Variables to capture state Multiple state variables: voter types Actions: Update poll stats (view results) What’s the same? different? Encapsulation Scope Hand-evaluation
Recap: Modeling State Data objects change over time Bank account, traffic light, Represent with variable(s) that change Mechanism: (set! var expr) Changes value to var to result of eval expr Supporting mechanism: (begin exp1 exp2 … expn): Evaluates all expressions: returns value of last
Defining a Poll What state captures a poll? What actions? Number of voters Number of voters in each category: For, against, undecided What actions? Add in new votes as come in Update Report current levels
What’s a vote? vote-type is 1) ‘for 2) ‘against 3) ‘undecided
Make-poll Contract: Purpose: -> (vote-type number -> (listof number)) Purpose: ;; To setup procedure to update standings Effect: update voters-for,against, undecided
Make-poll (define (make-poll) (let ((voters-for 0) (voters-against 0) (voters-undecided 0)) (lambda (vote-class new-votes) (let ((total-votes (+ new-votes voters-for voters-against voters-undecided))) (cond ((eq? vote-class 'for) (set! voters-for (+ voters-for new-votes))) ((eq? vote-class 'against) (set! voters-against (+ voters-against new-votes))) ((eq? vote-class 'undecided) (set! voters-undecided (+ voters-undecided new-votes))) (else (error "bad vote type"))) (list (/ voters-for total-votes) (/ voters-against total-votes) (/ voters-undecided total-votes))))))
Identity (define contest1 (make-poll)) (define contest2 contest1) Contest1 & contest2 “same” Use same state variables Contest3: Different Also poll – no shared state values
Encapsulation Local definition Defining as result shares variables State variables encapsulated in procedure Distinct for each invocation of make-poll Defining as result shares variables Separate invocation -> separate states
Summary Data objects change over time Capture in state variables