» Jun 3rd, 2008, category: C#, Python , Perm Link...

Iterator is concept of allowing iteration over container. In Python, you can do things like this:

days = ['mon', 'tue', 'wen', 'thu', 'sat', 'sun']
for day in days:
    print day

Any object in Python can have iterator by implementing inter method. If you look at built-in iterator object, you will see implementation of this function.

To traverse over iterator element, you can next() method and iterate until StopException is raised, for example:

days = ['mon', 'tue', 'wen', 'thu', 'sat', 'sun']
day_iter = days.__iter__() #or day_iter = iter(days)
while True:
    try:
        print day_iter.next()
    except StopIteration:
        break

Genertor is programming technique uses to produce multiple and iterative returning value. Shortly, generator is program that produce interator

For example, reading file. If file is big, reading a whole file into memory will comsume a lot of memory. To reduce memory usage, Generator programming style will return file line by line, allow programmer to interate over file. Anyway, If you need to read whole file, for example, parsing XML file. You will need to load file into memory but you still can iterate over XML element.

Python support Generator since Python2.2 (need to enable generator, i.e., from future import generators, Python2.3 and later enable generator by default). To create generator, simply use yield statement, for example:

import datetime
def next_day(days):
    current_day = datetime.datetime.today()
    while days:
        next_day = current_day + datetime.timedelta(days=1)
        current_day = next_day
        days -= 1
        yield next_day

This function return next number of days. Usage:

next_five_days = next_day(5)
for day in next_five_days:
     print day

Simple, isn't it?

These things in C#

In C#, concept of iterator is present in C# 2.0 but and is called "enumerators" and represented by the IEnumerator interface. It allow traversing by having MoveNext() method and also Reset() to reset iterator to initial state.

Getting iterator from any objects is by calling GetEnumerator() and such object has to implement IEnumerable interface. Example usage from (wikipedia),

// explicit version
IEnumerator<MyType> iter = list.GetEnumerator();
while (iter.MoveNext())
    Console.WriteLine(iter.Current);

// implicit version, since C#2.0
foreach (MyType value in list)
    Console.WriteLine(value);

Generator in C#

C# implements support for generator by adding new keyword "yield return", for example,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Utils
{
    public class DaysOfTheWeek : System.Collections.IEnumerable
    {
        string[] m_Days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };

        public System.Collections.IEnumerator GetEnumerator()
        {
            for (int i = 0; i < m_Days.Length; i++)
            {
                yield return m_Days[i];
            }
        }
    }
}

Usage:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Utils;
namespace Iterator
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the collection class
            DaysOfTheWeek week = new DaysOfTheWeek();

            // Iterate with foreach
            foreach (string day in week)
            {
                System.Console.Write(day + " ");
            }
            Console.ReadLine();
        }
    }
}

Comments

# geeks Oct 26th, 2009

That was an inspiring post,

Keep up the good work,

Thanks for bringing this up

# sicheresten Online Casino Nov 28th, 2009

Code which you give above,I just try to solve it .C# is language which is used for coding part when you want to develop some program or a software.I want to try date time function at home because i do not very much about that function.date time concept is not clear to me So I want to spend some more time on it.

# insurance Dec 30th, 2009

Wow! i agree! i’ve been searching for so long for a site where i could find everything that i want, and i’ve just found it!! really, i’ve visited your blog, and it’s amazing, i will keep visiting

Post your comment.

captcha