Concepts of Programming Languages

(Sean Pound) #1
8.3 Iterative Statements 373

Predefined iterators are used to provide iterative access to PHP’s unique
arrays. The current pointer points at the element last accessed through itera-
tion. The next iterator moves current to the next element in the array. The
prev iterator moves current to the previous element. current can be set or
reset to the array’s first element with the reset operator. The following code
displays all of the elements of an array of numbers $list:

reset $list;
print ("First number: " + current($list) + "<br />");
while ($current_value = next($list))
print ("Next number: " + $current_value + "<br \>");

User-defined iteration statements are more important in object-oriented
programming than they were in earlier software development paradigms,
because users of object-oriented programming routinely use abstract data types
for data structures, especially collections. In such cases, a user-defined iteration
statement and its iterator must be provided by the author of the data abstraction
because the representation of the objects of the type is not known to the user.
An enhanced version of the for statement was added to Java in Java 5.0.
This statement simplifies iterating through the values in an array or objects in
a collection that implements the Iterable interface. (All of the predefined
generic collections in Java implement Iterable.) For example, if we had an
ArrayList^5 collection named myList of strings, the following statement
would iterate through all of its elements, setting each to myElement:

for (String myElement : myList) {... }

This new statement is referred to as “foreach,” although its reserved word is
for.
C# and F# (and the other .NET languages) also have generic library classes
for collections. For example, there are generic collection classes for lists, which
are dynamic length arrays, stacks, queues, and dictionaries (hash table). All
of these predefined generic collections have built-in iterators that are used
implicitly with the foreach statement. Furthermore, users can define their
own collections and write their own iterators, which can implement the IEnu-
merator interface, which enables the use of foreach on these collections.
For example, consider the following C# code:

List<String> names = new List<String>();
names.Add("Bob");
names.Add("Carol");
names.Add("Alice");

...
5. An ArrayList is a predefined generic collection that is actually a dynamic-length array of
whatever type it is declared to store.

Free download pdf