foreach, an analogy

Bill Baxter dnewsgroup at billbaxter.com
Thu Oct 19 17:56:40 PDT 2006


Pragma wrote:
> Jarrett Billingsley wrote:
>> You can have:
>>
>> something.each((int item) {
>>     writefln(item);
>> });
> 
> I like the look of that.  I've been doing a lot of Javascript coding 
> with Prototype lately, and I really gotten used to using closures in 
> this way.

Apparently C# allows something similar.  From this page:
http://excastle.com/blog/archive/2005/05/18/1019.aspx
   "C# 2.0 will have some compiler magic for closures, but the syntax
    isn't as elegant as Ruby's — you need extra keywords, and the code
    block has to be inside the parentheses, which seems really clumsy
    after you get used to Ruby's syntax."

C# also has "foreach" which seems to do something very similar to D's:
(http://msdn.microsoft.com/msdnmag/issues/04/05/C20/#S3)
   BinaryTree<int> tree = new BinaryTree<int>();
   tree.Add(4,6,2,7,5,3,1);
   foreach(int num in tree.InOrder)
   {
      Trace.WriteLine(num);
   }

In D that would be
   foreach(int num; &tree.InOrder)
   {
      writefln(num);
   }

The only thing that really makes D's look more of a hack is that in D 
you need that '&'.  And maybe the mysterious ';' instead of a more 
readable 'in'.

Actually C# is eerily similar.  It also allows iteration over collections:
   string[] cities = {"New York","Paris","London"};
   foreach(string city in cities)
   {
      Console.WriteLine(city);
   }
using the magic "GetEnumerator()" method on string.  Aka opApply().

Note however, that there is no foreach_reverse.

> Aside from not being able to use break and continue to control the loop 
> behavior, I'd happily use a library that does this.  Prototype uses 
> "throw BREAK;" (where 'BREAK' is a constant defined elsewhere) which 
> might be a better looking solution, if a bit kludgey.

Seems like a 'yield' keyword is needed a la C#, Ruby, Python, and maybe 
others.

--bb



More information about the Digitalmars-d-announce mailing list