CS 227 lecture -*- Outline -*- * stacks as objects (12.3) Recall stacks from chapter 11 (program 11.1) Problem with that was that it was a global variable, clients could access it. couldn't have more than one stack in a program at a time was just the one object stack-maker will allow us to have more than one ** spec ------------------ STACK VALUES VALUE: a (stack T) value is a sequence of T objects, ADDITIONAL VOCABULARY: <> is the empty sequence if s1 = and s2 = , then adding x1 to the top of s2 is s1, removing x1 from the top of s1 is s2, the top of s1 is x1, printing s1 writes TOP: x1 x2 ... xn ------------------ this is used to specify the operations precisely the basic idea is to describe the values and to give the vocabulary needed to specify the operations (both of these constitute the abstract model) ------------------- BASIC OPERATIONS ON STACKS stack-maker: (-> () (stack of T)) ; ENSURES: result is a new stack ; with value <> type: (-> ((stack T)) string) ; ENSURES: result is "stack" empty?: (-> ((stack T)) boolean) ; ENSURES: result is #t iff 1st arg ; has value <> top: (-> ((stack T)) T) ; REQUIRES: 1st arg is not <> ; ENSURES: result is the top of 1st arg size: (-> ((stack T)) natural) ; ENSURES: result is length of 1st arg push!: (-> ((stack T) T) void) ; MODIFIES: 1st arg ; EFFECT: make the value of 1st arg ; be adding 2nd arg to the top of ; the old 1st arg value pop!: (-> ((stack T)) void) ; REQUIRES: 1st arg is not <> ; MODIFIES: 1st arg ; EFFECT: remove the top of 1st arg print: (-> ((stack T)) void) ; EFFECT: print the 1st arg value ------------------ ** impl ------------------- FILL IN THE IMPLEMENTATION (define stack-maker ; TYPE: (-> () ((stack T))) (lambda () (let ((stk '())) (lambda msg (case (1st msg) ((type) "stack") ((empty?) _____________) ((push!) ______________________________ ______________________________) ((top) (if ____________ ____________________ ___________________)) ((pop!) (for-effect-only (if ______________ ________________________ _______________________))) ((size) _______________) ((print) (display "TOP: ") (for-each _____________________________ stk) (newline)) (else (delegate base-object msg))))) )) ------------------- How could you define a class sized-stack maker that has a faster size operation? Cache the size (as a gauge (!) or a variable), then update it in push! and pop! Implement this, and call its type "stack" also Note that both kinds of stacks can be used at once in a program and no-one can tell the difference