foreach

bearophile via Digitalmars-d digitalmars-d at puremagic.com
Sat Jun 14 08:43:23 PDT 2014


The idea of using code like this (only one or the other should be 
allowed) is rather natural, it breaks nothing, it avoids the 
programmer to introduce a variable that is not needed, making the 
code less noisy:

foreach (;0 .. 10) {...}
foreach (0 .. 10) {...}

I don't see the need for so many posts against this simple and 
innocous idea that's a small improvement. Improvements don't need 
to be large to be good, if their price is correspondingly small 
(as in this case). (With an attitude like the current one no 
small positive feature like the "_" to separate digits in numbers 
literals could have seen the light).


With a little breaking change "_" could become a name that can't 
be referenced, so you can also do:

foreach (_; 0 .. 10) { // OK
   foreach (_; 0 .. 20) { // OK
     writeln(_); // syntax error
   }
}


Or:

foreach (immutable i, _; items) {...}


The _ can also be used as "don't care" for tuple unpacking, this 
is a very important usage:

t{_, b} = fooAB();


And in switch on structs (that contain the optional "unapply" 
method):

switch (foo) {
   case Foo(x, _, _): writeln(x); break;
   default:
}



An alternative idea is to use "__", that is a reserved 
identifier. It's a little longer but I think it's still 
acceptable:


foreach (__; 0 .. 10) { // OK
   foreach (__; 0 .. 20) { // OK
     writeln(__); // syntax error
   }
}

foreach (immutable i, __; items) {...}

t{__, b} = fooAB();

switch (foo) {
   case Foo(x, __, __): writeln(x); break;
   default:
}


Bye,
bearophile


More information about the Digitalmars-d mailing list