Why tuples are not ranges?

Mr.Bingo Bingo at Namo.com
Thu Jun 28 17:00:37 UTC 2018


On Thursday, 28 June 2018 at 16:02:59 UTC, Alex wrote:
> On Thursday, 28 June 2018 at 14:35:33 UTC, Mr.Bingo wrote:
>> Seems like it would unify things quite a bit.
>
> Yeah... this is, because you can't popFront on a tuple, as the 
> amount of entries is fixed. You can, however, popFront on every 
> range.
>
> But as Timoses wrote you can easily make a range out of a 
> tuple, for example by slicing:
>
> ´´´
> import std.typecons, std.range, std.array, std.algorithm, 
> std.stdio;
>
>     void main()
>     {
>         auto t = tuple(3,4,5,6);
> 		auto m = [t[]];
>         writeln(m.map!(a => 3*a).sum());
>     }
> ´´´

But is this going to be optimized?

BTW, surely the tuple has a popFront! Just pop the last element 
and returns a new tuple.

That is, a tuple is a range! Just because it doesn't implement 
the proper functions doesn't mean it can't do so.

It is clearly easy to see if a tuple is empty, to get the front, 
and to pop the front and return a new tuple with n - 1 elements, 
which is really just the tuple(a sliced tuple, say) with the 
first member hidden.

Since a tuple is fixed at compile time you can "virtually" pop 
the elements, it doesn't mean that a tuple is not a range.

So, maybe for it to work the compiler needs to be able to slice 
tuples efficiently(not convert to dynamic arrays).

This is moot if the compiler can realize that it can do most of 
the work at compile time but I'm not so sure it can.

I mean, if you think about it, the memory layout of a tuple is 
sequential types:

T1
T2
...

So, to popFront a tuple is just changing the starting offset.



More information about the Digitalmars-d-learn mailing list