Lecture 21 : More programs with memory The vending machine example -- code in lec21 dir (ready for posting) -------------------------------- Keeping Count You may have seen web pages that tell you how many visitors they've had, or been asked to take a ticket with a number when waiting in line. Both of these applications involve remembering counts of numbers. Let's write a simple ticket counter that gives tickets up to number 4, then starts over with tickets numbered 1. Specifically, we want a function get-ticket that gives us the next ticket number. We need a variable for the ticket number ; ticketnum : number ; stores the last ticket number handed out (define ticketnum 0) ;; get-ticket :?? -> number ;; produces the next ticket number ;; EFFECT: increments ticketnum, or restarts it at 1 (define (get-ticket ??) (begin (cond [(= ticketnum 4) (set! ticketnum 1)] [else (set! ticketnum (+ 1 ticketnum))]) ticketnum)) What does this need as input? Nothing, really. Get-ticket is an example of a function that takes no input yet produces output each time you use it. It is fine to write such programs, just leave out the names of inputs and the input in the contract. ;; get-ticket : -> number ;; produces the next ticket number ;; EFFECT: increments ticketnum, or restarts it at 1 (define (get-ticket) (begin (cond [(= ticketnum 4) (set! ticketnum 1)] [else (set! ticketnum (+ 1 ticketnum))]) ticketnum)) Note that this seems to break yesterday's guideline that we use set! when we have one function that changes a value when another needs to use that value. We could think of the person who requests the ticket as the thing that uses the changed value. Another way to phrase our requirements is Use variables and set! when - two functions must access the same data and one of those functions changes that data - the output of a function needs to be different over time when called with the same inputs Note to those of you with some prior programming experience: you are used to using assignment in other ways as well. Don't try to do that here. Programming styles vary across languages, based on the way that language is designed. Other languages are designed so that heavy use of assignment is the standard way of programming. Scheme is different. We're also trying to help you see when you _need_ assignment because the program you are writing demands it, versus when you _could_ use it to get code running. You should only use set! if your program satisfies one of the two criteria stated above.