A possible suggestion for the Foreach loop

Timon Gehr timon.gehr at gmx.ch
Thu Aug 22 05:56:52 PDT 2013


On 08/21/2013 07:45 PM, Andrei Alexandrescu wrote:
> On 8/21/13 4:52 AM, John Colvin wrote:
>> On Wednesday, 21 August 2013 at 02:46:06 UTC, Dylan Knutson wrote:
>>> Hello,
>>>
>>> I'd like to open up discussion regarding allowing foreach loops which
>>> iterate over a tuple of types to exist outside of function bodies.
>>
>> I would *LOVE* to have this.
>>
>> however, once we go down that route, it would be very tempting to allow
>> a whole lot of other compile-time imperative style programming. Which
>> would be awesome.
>
> Not necessarily. We could allow "static foreach" as a functional
> construct that binds in turn a symbol to each element in a collection.
> ...

Yup.

> A static foreach in conjunction with string mixins would be great for
> simplifying code generation, e.g. "for each method in that class
> generate a method here".
>

AFAIK one only reason why it hasn't made it in yet were implementation 
issues related to DMD internals? The design was discussed in 2007's 
dconf IIRC.

>
> Andrei
>
>

We really need to define a consistent semantics for compile time symbol 
manipulation though.

Eg:

class C{
     int a;
     static foreach(x;__traits(allMembers,C)){
         mixin("int "~__traits(identifier,x)~"b;");
     }
}

What is this supposed to do? "class C{ int a,ab; }"? Non-terminating 
compilation? Error?

My best guess is that the above code should be illegal, but there is a 
lot of similar code already out in the wild that works by chance. Eg. I 
guess some of Manu's bindings only work by luck. Thrift for D also 
contains one or two questionable constructs, as David has shown me 
recently. (It is possible that this is related to the recent breakage, 
DMD does not necessarily behave consistently w.r.t. to this kind of code 
across versions.)

Most of the times this has been brought up it was simply ignored, but it 
is a glaring hole in D's design.


More information about the Digitalmars-d mailing list