Concepts of Programming Languages

(Sean Pound) #1
11.5 Parameterized Abstract Data Types 503

myStack.push(29)
puts "Top element is (should be 29): #{myStack.top}"
myStack.pop
puts "Top element is (should be 42): #{myStack.top}"
myStack.pop

# The following pop should produce an
# error message - stack is empty
myStack.pop

Recall that the notation #{variable} converts the value of the variable to a
string, which is then inserted into the string in which it appears. This class
defines a stack structure that can store objects of any type.

11.4.6.4 Evaluation
Recall that in Ruby, everything is an object and arrays are actually arrays of
references to objects. That clearly makes this stack more flexible than the
similar examples in Ada, C++, and Java. Furthermore, simply by passing the
desired maximum length to the constructor, objects of this class could have
any given maximum length. Of course, because arrays in Ruby have dynamic
length, the class could be modified to implement stack objects that are not
restricted to any length, except that imposed by the machine’s memory capac-
ity. Because the names of class and instance variables have different forms,
Ruby has a slight readability advantage over the other languages discussed
in this section.

11.5 Parameterized Abstract Data Types


It is often convenient to be able to parameterize abstract data types. For exam-
ple, we should be able to design a stack abstract data type that can store any
scalar type elements rather than be required to write a separate stack abstrac-
tion for every different scalar type. Note that this is only an issue for static
typed languages. In a dynamic typed language like Ruby, any stack implicitly
can store any type elements. In fact, different elements of the stack could be
of different types. In the following four subsections, the capabilities of Ada,
C++, Java 5.0, and C# 2005 to construct parameterized abstract data types are
discussed.

11.5.1 Ada
Generic procedures in Ada were discussed and illustrated in Chapter 9. Pack-
ages can also be generic, so we can construct generic, or parameterized, abstract
data types.
Free download pdf