foreach syntax, std.mixin
dsimcha
dsimcha at yahoo.com
Sun Nov 8 09:10:46 PST 2009
What are the chances that D gets auto tuple unpacking for foreach loops before
D2 goes gold? In other words, it would be nice to write:
uint[] foo = [1,2,3,4,5];
uint[] bar = [6,7,8,9,10];
foreach(a, b; zip(foo, bar)) {
// Does what you think it does.
}
Also, how about foreach over ranges with an index variable? For example:
foreach(index, elem; chain(foo, bar)) {
// Does what you think it does.
}
If these aren't going to happen, would it be worth having in Phobos a
std.mixin module (I've already considered such a thing a few times here) that
would allow someone writing a range to add goodies like these to structs and
classes with a single line of code? For example:
struct MyRange {
Tuple!(float, float) _front;
bool _empty;
typeof(_front) front() {
return _front;
}
void popFront() {
// do stuff.
}
bool empty() {
return _empty;
}
mixin(UnpackTupleForeach);
mixin(IndexForeach);
}
The mixin(UnpackTupleForeach) would make this work:
foreach(float float1, float float2; MyRange.init) {}
The mixin(IndexForeach) would make this work:
foreach(size_t index, float floatTuple; MyRange.init) {}
This would work via opApply, which some don't like for efficiency reasons.
It's been shown a while back that, while opApply does have some overhead, it's
pretty small and LDC actually optimizes it out.
More information about the Digitalmars-d
mailing list