Repost: make foreach(i, a; range) "just work"

Regan Heath regan at netmail.co.nz
Mon Feb 24 02:31:36 PST 2014


On Fri, 21 Feb 2014 16:59:26 -0000, Justin Whear  
<justin at economicmodeling.com> wrote:

> 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

Thanks.  I understand this now, I had forgotten about tuple  
unpacking/flattening.  DMD supports at least 4 distinct types of foreach.   
The range foreach is the one which I want an index/count added to, and  
this change will have no effect on the tuple case shown above.

It should "just work", and there is no good reason not to make it so.

R

-- 
Using Opera's revolutionary email client: http://www.opera.com/mail/


More information about the Digitalmars-d mailing list