4.2.5.4 Iterating Over a Sequence

Each time a Sequence procedure is invoked it returns the next in a series of items. They are called repeatedly using a Do-Sequence construct or individually using the Churn command. In either case an opaque Local variable is implicitly declared to hold the current state of the sequence between calls.


A Sequence procedure declares an Exit parameter that determines the type of value returned on each call. The type of the Result variable in a DO-Sequence or Churn command receives the Exit parameter for the sequence. The Result iterator can either be a Local variable or implicitly declared.

When the Exit parameter in a Sequence procedure is a pointer and the Result variable is not, then the item pointed to is copied into the Result variable. Since the pointer is dereferenced it must always point to data. It cannot return a null pointer or a constant Parcel value. Otherwise a fault exception will be raised due to an invalid pointer reference.

The With clause is optional and is used to resume a partially completed Sequence. The variable, It, is implicitly declared and is a handle referencing the internal data tracking the state of the Sequence.

After leaving a Do-Sequence loop, the Result iterator is set to the last value retrieved from the sequence. If the sequence ran through to completion, the With variable is in a closed state. When partially completed and there is a With clause then you can resume the Sequence.


Another way to run a Sequence is to declare a variable in the From clause. The the variable must have a structure type whose name is the same as the name of the Sequence procedure. This is a shorthand notation used to iterate over a data structure (e.g. a container).


As an example the Stack class is a container that includes a Sequence procedure named Stack as well that returns each element in the stack. This is equivalent coding "Stack( My.Stack )" on the From clause.


A Do-Sequence loop can resume iterating over an active sequence via the state reference on a With clause. If the sequence is inactive then the loop is skipped and the Result variable is unchanged.


Switches on a With clause variable can be used to detect the current state of a Sequence.


This example shows how to code a simple Sequence and also shows that sequences can be chained together. This program (Twin) uses a Sequence (Prime.Twin) to generate prime twins within a designated range.


Prime.Twin then calls another Sequence, Prime, that returns prime numbers starting at a given value. The Prime Sequence is a member of the Math.Integer Class in the Basis library.


This Class declares these two procedures as members and is needed to build the program.

Iterating Over an Array

Churn Through a Sequence