# 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:18:8-23:13: --source code: () -> ( if i >= #x then StopIteration else ( r := x#i; i = i + 1; r))) | symbol class value location of symbol | ------ ----- ----- ------------------ | i : ZZ -- 0 ../../../../../../../Macaulay2/m2/iterators.m2:17:5-17:6 | x : List -- {1, 2, 3} ../../../../../../../Macaulay2/m2/iterators.m2:16:25-16:26

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

## Functions and methods returning an iterator :

• "accumulate(Function,Thing)" -- see accumulate -- apply a binary operator repeatedly
• "accumulate(Function,Thing,Thing)" -- see accumulate -- apply a binary operator repeatedly
• apply(Thing,Function) -- apply a function to an object with an iterator
• select(Thing,Function) -- select elements from an object with an iterator

## Methods that use an iterator :

• "iterator(Iterator)" -- see iterator -- get an iterator
• Iterator | Iterator (missing documentation)
• "next(Iterator)" -- see next -- get the next object from an iterator

## For the programmer

The object Iterator is , with ancestor classes FunctionClosure < Function < Thing.