Iterating over the tupleof of a struct

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 23 13:34:35 PDT 2014


On 08/23/2014 10:21 AM, Meta wrote:
> On Saturday, 23 August 2014 at 01:56:06 UTC, Dicebot wrote:
>> On Saturday, 23 August 2014 at 01:32:13 UTC, Meta wrote:
>>> On Saturday, 23 August 2014 at 01:24:10 UTC, Meta wrote:
>>>> What is happening here? Are these two extra ulongs the offsets of
>>>> the fields in the struct?
>>>
>>> And I just realized that that's obviously not the case. It's just an
>>> iteration variable. Problem solved.
>>
>> It is same with arrays:
>>
>> int[] arr = [ 1, 2, 3 ];
>>
>> // ok, iterates elements
>> foreach (elem; arr) { }
>>
>> // also ok, iterates elements + counts current index
>> foreach (index, elem; arr) { }
>
> Yeah, I got confused as I expected
>
>      foreach (val1, val2; test.tupleof)
>      {
>          //...
>      }
>
> To destructure the result of test.tupleof, but I just got an iteration
> variable instead.

There are a number of inconsistencies around tuples. The behavior you 
expect is present for ranges that return tuple fronts:

import std.stdio;
import std.typecons;
import std.range;

void main()
{
     auto t = [ tuple(1.5, 100), tuple(2.5, 200) ];

     foreach (a, b; t.retro) {
         writefln("%s, %s", a, b);
     }
}

Because t.retro is a range, the foreach extracts the members of the 
tuple and we get the folloing output:

2.5, 200
1.5, 100

Now, remove the .retro part; the range becomes a slice, in which case 
'a' becomes the iteration counter and 'b' becomes the tuple value:

0, Tuple!(double, int)(1.5, 100)
1, Tuple!(double, int)(2.5, 200)

Is that a WAT? :)

Ali



More information about the Digitalmars-d-learn mailing list