Macaulay2 » Documentation
Packages » Macaulay2Doc :: Iterator
next | previous | forward | backward | up | index | toc

Iterator -- class for iterators

Description

This is a class designed to simplify writing iterator methods. Each instance is a nullary FunctionClosure that serves as the next method for the iterator.

i1 : iter = iterator {1, 2, 3}

o1 = iterator {1, 2, 3}

o1 : Iterator
i2 : code iter

o2 = ../../../../../Macaulay2/m2/iterators.m2:21:7-26:12: --source code:
         () -> (
             if i >= #x then StopIteration
             else (
                 r := x#i;
                 i += 1;
                 r)))
     | symbol  class  value      location of symbol
     | ------  -----  -----      ------------------                                  
     | i       ZZ     0          ../../../../../Macaulay2/m2/iterators.m2:20:4-20:5  
     | x       List   {1, 2, 3}  ../../../../../Macaulay2/m2/iterators.m2:19:24-19:25

Each call of next iter is equivalent to iter().

i3 : next iter

o3 = 1
i4 : iter()

o4 = 2
i5 : next iter

o5 = 3
i6 : iter()

o6 = StopIteration

o6 : Symbol

Every Iterator object is an iterator for itself.

i7 : primes = Iterator (
         p := 2;
         () -> (
             r := p;
             p = nextPrime(p + 1);
             r));
i8 : iterator primes === primes

o8 = true

However, we cannot "rewind" an Iterator object. Every time that it is iterated upon using for, scan, etc., iteration will resume where it left off previously.

i9 : for p in primes list if p > 20 then break else p

o9 = {2, 3, 5, 7, 11, 13, 17, 19}

o9 : List
i10 : for p in primes list if p > 20 then break else p

o10 = {}

o10 : List

Contrast this with most other classes with the iterator method installed, like, strings, for which a new Iterator object is created every time it is iterated upon, and so iteration starts over from the beginning

i11 : s = "Hello, world!"

o11 = Hello, world!
i12 : for c in s list c

o12 = {H, e, l, l, o, ,,  , w, o, r, l, d, !}

o12 : List
i13 : for c in s list c

o13 = {H, e, l, l, o, ,,  , w, o, r, l, d, !}

o13 : List

See also

Functions and methods returning an iterator :

Methods that use an iterator :

For the programmer

The object Iterator is a self initializing type, with ancestor classes FunctionClosure < Function < Thing.