how to expand tuple?

Philippe Sigaud via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 1 13:50:44 PDT 2014


On Sat, Nov 1, 2014 at 9:34 PM, Suliman via Digitalmars-d-learn
<digitalmars-d-learn at puremagic.com> wrote:
> Few questions.
>
> 1. In examples tuples are created with keyword auto. Can I create them with
> another keyword. Or auto mean structure of data, that have not standard type
> like (int or string)?

`tuple' is a function defined in the std.typecons module. It's a
helper function to create Tuple!(T...), a templated struct acting as a
tuple.

Don't forget the type will depend on the types of the arguments, so:

auto tup = tuple(1.0, "abc", [2,3]);

contains a float, a string and an array of int's, so it's type is
Tuple!(float, string, int[]):

Tuple!(float, string, int[]) tup = tuple(1.0, "abc", [2,3]);

It's a bit long to type, so most people prefer using `auto' for such
declarations.



>
> 2. How ti expend tuple? I tried to do:
>
>    auto imglist = tuple("aaa");
>    imglist.expand["sss"];
>    writeln(imglist);
>
> but got very strange error:
> app.d(30): Error: cannot implicitly convert expression ("sss") of type
> string to  uint

Expand, you mean, as in appending to a tuple? It can be done, but it
will create a new type.

First, tup.expand gives you access to the 'raw' tuple ( a template
parameter list, to be precise) underneath Tuple!(T...). The returned
value can be indexed, sliced and its length is known at compile time.

Continuing with my example:

auto first = tup.expand[0]; // "1.0"
auto slice = tup.expand[1..$]; // ("abc", [2,3])
auto len = tup.expand.length; // 3, since tup has three elements.

That explains the error you get: imglist.expand is a bit like a
vector: it can be indexed, but with uint, not with a string. I thought
you were expanding it, but to the compiler you were trying to index
using a string.


If you really want to append to a tuple, you must create a new
variable, since the augmented tuple will have a different type:

auto tup2 = tuple(tup.expand, 'd'); // tup2 == (1.0, "abc", [2,3], 'd')

The type of tup2 is then Tuple!(float, string, int[], char)


Note that, in your case, as you're using only strings, an array of
strings would probably be easier to use.


More information about the Digitalmars-d-learn mailing list