6.20.2.3 Attaching a counter to an iterator

The collections.enumerate(T) module provides a way to attach a counter to an iterator. There are two functions, both called enumerate:

Here’s a simple example:

from collections.enumerate(T=int) access enumerate;
int[] x = {1, 4, 9, 16};
for (var ab : enumerate(x))
  write('Element ' + string(ab.k) + ' is ' + string(ab.v));

which outputs

Element 0 is 1
Element 1 is 4
Element 2 is 9
Element 3 is 16

Note that enumerate is not necessarily worthwhile for arrays since they are already indexed by integers:

int[] x = {1, 4, 9, 16};
for (int i=0; i < x.length; ++i)
  write('Element ' + string(i) + ' is ' + string(x[i]));

The enumerate utility is more useful for structures that do not have a builtin integer index (such as Map and Set).