gs@mit-eddie.UUCP (Gordon Strong) (12/09/83)
As promised, here is a short CLU implementation of a stack. There are some notes following the code. ------begin code---- % a simple parameterized stack abstraction stack = cluster[t:type] is create, push, pop, empty rep = array[t] %a stack is represented as an array create = proc() returns(cvt) return(rep$[]) %returns an empty stack end create push = proc(s:cvt,elt:t) rep$addh(s,elt) %adds an element to the top of the stack end push pop = proc(s:cvt) returns(t) signals(empty_stack) return(rep$remh(s)) %pops the stack except when bounds: %except when the stack is empty signal empty_stack end end pop empty = proc(s:cvt) returns(bool) return(rep$empty(s)) %is the stack empty? end empty end stack ----end code----- Procedures are called externally by specifying the module and procedure name (e.g stack$push(stk,var) -- in general, module$proc(args). A few notes: the stack can be of any type. You choose the type when you create the stack (e.g. s=stack[int]$create() ). Notice how use is made of built-in CLU operations for dealing with arrays (addh, remh, empty). The choice of the rep is an important consideration in CLU, as it influences the ease of coding. Wherever 'rep' is used, array[t] is substituted. The actual type is chosen when it is used (i.e. in the same program, you can have different stacks of different types, all using the same abstraction). You can also see how exception handling works in the pop procedure. When an error occurs (such as trying to remove an element from an empty stack) an exception is raised. These signals can be caught and resignaled. This is a very neat and clean mechanism for dealing with exceptions. Remember this is a very simple module, but it does give you an idea of how the abstractions work. If anyone wants to see other examples, let me know. -- Gordon Strong decvax!genrad!mit-eddie!gs GS@MIT-XX