[Mono-list] Iterator hello world.

Erik Bågfors erik@bagfors.nu
07 May 2003 10:56:00 +0200


On Wed, 2003-05-07 at 06:12, Miguel de Icaza wrote:
> The right way of writing hello world with iterators:
> 
> using System.Collections;
> using System;
> class Hello {
> 
> 	static IEnumerable GetMessage ()
> 	{
> 		yield "Hello";
> 		yield ", ";
> 		yield "World";
> 		yield "\n";
> 	}
> 
> 	static void Main ()
> 	{
> 		foreach (string s in GetMessage ())
> 			Console.WriteLine (s);
> 	}
> }


To cool,
ofcource the Console.WriteLine should be Console.Write :)

Anyway, Being a big fan of the ruby language (which makes lot's of use
of iterators and "yield") I tried playing around with this alittle and
got into some problems I cannot explain.

I wrote the following small program (simply added another iterator to
the same program)

using System.Collections;
using System;

class Hello {
    static IEnumerable GetMesssage()
    {
	yield "Hello";
	yield ", ";
	yield "World";
	yield "\n";
    }

    static IEnumerable DoTimes(int x)
    {
	for (; x > 0; x--)
	    yield x;
    }
    

    static void Main()
    {
	foreach (string s in GetMesssage()) 
	    Console.Write(s);

	foreach (int x in DoTimes(3)) 
	    Console.WriteLine(x);
	    
    }
}

For some reason this doesn't work (doesn't even compile).  If I remove
GetMessage and the call to GetMessage everything works!

Is this a bug or shouldn't it be possible to have to iterators in the
same class?

In ruby you also have blocks which could be viewed as anonymous
methods.  For example you could write this

DoTimes(3) {|x| print(x) }

I think I read that something like that was about to show up in C#? Am I
correct?

/Erik

-- 
erik@bagfors.nu
fingerprint: 6666 A85B 95D3 D26B 296B 6C60 4F32 2C0B 693D 6E32