What is the difference between an Iterator and a Generator?
There's too much Python here, and too many people saying generators are the only way to implement an infinite iterator. Here's the example I mentioned (squares of all natural numbers) implemented in C#. ExplicitSquares explicitly implements an iterator (called IEnumerator in C#). ImplicitSquares uses a generator to do the same thing. Both are infinite iterators and have no backing collection. The only difference is whether the state machine is spelled out, or alternatively a generator is used.
using System.Collections;
using System.Collections.Generic;
using System;
class ExplicitSquares : IEnumerable
{
private class ExplicitSquaresEnumerator : IEnumerator
{
private int counter = 0;
public void Reset()
{
counter = 0;
}
public int Current { get { return counter * counter; }}
public bool MoveNext()
{
counter++;
return true;
}
object IEnumerator.Current { get { return Current; } }
public void Dispose(){}
}
public IEnumerator GetEnumerator()
{
return new ExplicitSquaresEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
class ImplicitSquares : IEnumerable
{
public IEnumerator GetEnumerator()
{
int counter = 1;
while(true)
{
int square = counter * counter;
yield return square;
counter++;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class AllSquares
{
private static readonly int MAX = 10;
public static void Main()
{
int i = 0;
foreach(int square in new ExplicitSquares())
{
i++;
if(i >= MAX)
break;
Console.WriteLine(square);
}
Console.WriteLine();
int j = 0;
foreach(int square in new ImplicitSquares())
{
j++;
if(j >= MAX)
break;
Console.WriteLine(square);
}
}
}