Andrei:
> > Is unpaking inside foreach too supposed to work? This is quite useful:
> > auto somepairs = [tuple(1, "foo"), tuple(10, "bar")];
> > foreach ((x, name); somepairs) {}
>
> This is a bit risky as foreach (x, name; somepairs) would mean something
> completely different.
That's unfortunate.
foreach(index,item;somearray) was a handy shortcut designed not thinking enough
about its wider consequences :-(
In Python iterables yield one item, and you are allowed to unpack items if they
are composed by more than one item, and to use enumerate() to yield on
(index,item) 2-tuples.
Removing the optional index from iterating on both arrays and associative
arrays (so you need to use something like enumerate() if you want array indexes
too, and a AA.byPairs() method if you want key-value 2-tuples of AAs) probably
isn't an option because it breaks too much D code.
This looks a bit less bug-prone:
foreach (tuple(x, name); somepairs) {}
------------------
A third place where tuple unpacking is handy is in switch statements.
Supporting switching on structs allows to switch on tuples too. If you allow
tuple unpacking syntax here too, you get a poor's man pattern matching, that
despite being simple is probably useful.
switch (sometuple) {
case (0, y): ...
case (x, 0): ...
case (x, y): ... // no default needed, this catches all other cases
}
(Note: both AA.byPairs() and switch on structs are useful even if they don't
get any special support for tuples.)
Bye,
bearophile