Repost: make foreach(i, a; range) "just work"
Justin Whear
justin at economicmodeling.com
Fri Feb 21 08:59:26 PST 2014
On Fri, 21 Feb 2014 10:02:43 +0000, Regan Heath wrote:
> On Thu, 20 Feb 2014 16:30:42 -0000, Justin Whear
> <justin at economicmodeling.com> wrote:
>
>> On Thu, 20 Feb 2014 13:04:55 +0000, w0rp wrote:
>>>
>>> More importantly, this gets in the way of behaviour which may be
>>> desirable later, foreach being able to unpack tuples from ranges.
>>> I would like if it was possible to return Tuple!(A, B) from front()
>>> and write foreach(a, b; range) to interate through those thing,
>>> unpacking the values with an alias, so this...
>>>
>>> foreach(a, b; range) {
>>> }
>>>
>>> ... could rewrite to roughly this. (There may be a better way.)
>>>
>>> foreach(_someInternalName; range) {
>>> alias a = _someInternalName[0];
>>> alias b = _someInternalName[1];
>>> }
>>
>> Tuple unpacking already works in foreach. This code has compiled since
>> at least 2.063.2:
>>
>> import std.stdio;
>> import std.range;
>> void main(string[] args)
>> {
>> auto tuples = ["a", "b", "c"].zip(iota(0, 3));
>>
>> // unpack the string into `s`, the integer into `i`
>> foreach (s, i; tuples)
>> writeln(s, ", ", i);
>> }
>
> Does this work for more than 2 values? Can the first value be something
> other than an integer?
>
> R
Yes to both questions. In the following example I use a four element
tuple, the first element of which is a string:
import std.stdio;
import std.range;
void main(string[] args)
{
auto tuples = ["a", "b", "c"].zip(iota(0, 3), [1.2, 2.3, 3.4], ['x',
'y', 'z']);
foreach (s, i, f, c; tuples)
writeln(s, ", ", i, ", ", f, ", ", c);
}
Compiles with dmd 2.063.2
More information about the Digitalmars-d
mailing list