On Tue, 02 Aug 2011 15:15:52 +0200, bearophile <[email protected]> wrote:

5.1) The most basic one is unpacking a tuple locally, inside a function.
5.2) Another common situation is unpacking a small tuple inside a foreach statement, when you iterate on a collection of tuples.

I would argue these two are the most important ones.

5.3) Another usage (quite common in Haskell and similar languages) is to unpack a tuple in the signature of a function. Haskell even allows to give names at the same time to both fields and to the whole tuple.

This is less important, I think.

Other operations are:
6) Slice a tuple like a Python/D array: tup[1..3]. (This is already supported in D, but you can't use the normal slice syntax, you need to use tup.slice!(1, 3) ).
7) Concat two or more tuples (using ~ and ~= operators).

Note that ~= cannot work, as the result of the concatenation has a different type than the left hand side. (Unless, of course, the right hand side is the empty tuple :-)

5.3) This is already possible in D using the typetuple coming from a tuple using the (undocumented?) .tupleof. But this has the problem of losing some safety, this compiles with no errors:

import std.typecons;
void bar(int i, string s) {}
void main() {
    auto t1 = tuple(1, "foo");
    bar(t1.tupleof);
    auto t2 = tuple(1);
    auto t3 = tuple("foo");
    bar(t2.tupleof, t3.tupleof);
}

This is because of the conflation of TypeTuple (the compiler thing) and Tuple (the sane type thing). That code works because .tupleof is a TypeTuple.

We need this functionality because of things like std.traits.ParameterTypeTuple (or indeed Tuple itself uses a TypeTuple internally).

The built in compiler tuple could use a new name, badly, to disperse the confused situation with sane tuples. AliasSequence or something :-)

In Python there are more features similar to the point (5). Yo are allowed to unpack a dynamic array too into variables, and even a lazy generator. This is so handy and useful that I have suggested to allow the same thing in D too:
http://d.puremagic.com/issues/show_bug.cgi?id=6383

I think that as well as tuples, any range should be unpackable, and I think it should be implemented via syntactic rewrite.

Translate this:

auto (a, rest...) = myRange;

into

static assert (isInputRange!myRange);
assert (!myRange.empty);
auto a = myRange.front;
myRange.popFront;
rest = myRange;

Equivalently with bidirectional ranges, and any number of unpacked elements.


I wonder how the auto(...) syntax works with existing variables. For example, in python:

a, b = b, a # swap!

Reply via email to