Range Over Iterators in Chapel
On this page
In this example, we will use Chapel to demonstrate the concept of iterators, similar to the example shown previously in another language. Starting with version 1.23, the language has added support for iterators, which lets us iterate over pretty much anything.
Let’s look at the List
type that we will define. The list will consist of elements, and we’ll add an AllElements
iterator to return all elements in the list. We will also show how to create a Fibonacci sequence iterator.
Here’s the full source code.
Explanation
List and Element Definition:
- The
element
record defines the structure for storing elements in the list, with anext
pointer and a valueval
. - The
List
record containshead
andtail
pointers to manage the list.
- The
Push Method:
- The
push
method adds a new value to the list. If the list is empty, it initializes bothhead
andtail
with the new element. If not, it links the new element to thetail
and updatestail
.
- The
AllElements Iterator:
- The
allElements
iterator iterates over the list, yielding each value. This iterator can be used in afor
loop to traverse the list.
- The
Fibonacci Iterator:
- The
genFib
function generates an indefinite sequence of Fibonacci numbers and continues as long as thefor
loop inmain
does not break.
- The
Main Function:
- Demonstrates pushing elements into the list.
- Uses the
allElements
iterator to print each element. - Collects all elements into an array and prints it.
- Generates and prints Fibonacci numbers stopping at 10 using the
genFib
iterator.
This example illustrates how Chapel’s iterators and lists can be used to manage and traverse collections of data efficiently.