The Gang of Four (GoF) Iterator
The Iterator design pattern prescribes interfaces for accessing container elements. "Sequential" is right in the charter of the Iterator pattern as defined in the classic Gang of Four (GoF) book Design Patterns: Elements of Reusable Object-Oriented Software [7]:
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
When getting into details, the authors amend this simple definition in a number of important ways, such as allowing nonsequential access, but without any attempt at systematization.
Iterator prescribes the following interface for iteration over a container with elements of type T:
interface Iterator { void First(); // Restart iteration void Next(); // Advance to next item bool IsDone(); // Are we done yet? T CurrentItem(); // Get current item }
Many of today's object-oriented libraries follow this mold. Some drop the First method in favor of a more general methodcalled Clone, for examplewhich returns another Iterator: If you want to save iteration bread crumbs as you move along, you can just create independent copies of the Iterator object and store them in separate variables. This is more general than just restarting iteration from the first element with First.
In brief, functional languages and object-oriented languages foster distinct iteration styles. The two styles have some differences, but both focus on forward iteration. Focusing on forward iteration may blind us to the necessity of backward or random access iteration. Going backward through a container using its GoF-style iterator is virtually impossible unless you take the hit of copying the whole thing first. And this could have been as good as it gets, had the STL not come about.