Skip to content

Sequence, iterator, and coordinate protocols

jckarter edited this page Nov 18, 2010 · 10 revisions

Iterator sequences

At the most general level, a sequence type is any type for which the iterator function is defined. The iterator object is used to access the elements of the sequence one at a time. The type of the iterator object must support the hasNext? and next operations. hasNext? returns a Bool value indicating whether there are elements left to be accessed, and next accesses the next available value. The behavior of next is undefined if hasNext? returns false. Here is an example sequence object Iota that produces a sequence of integers via an IotaIterator:

  record Iota (n: Int);
  record IotaIterator (i: Int, n: Int);

  overload iterator(iota: Iota) = IotaIterator(0, itoa.n);
  overload hasNext?(ii: IotaIterator) = ii.i < ii.n;
  overload next(ii: IotaIterator) {
      var i = ii.i;
      inc(ii.i);
      return i;
  }

We can now use the Iota object in a for loop:

  for (n in Iota(10))
      println(n, " is the loneliest number");

As indicated in Syntax desugaring, a for loop expands to a sequence of iterator, hasNext? and next calls looking like this:

  {
      ref _x = b;
      var _y = iterator(_x);
      while (hasNext?(_y)) {
          ref a = next(_y);
          c;
      }
  }

Clone this wiki locally