A Discussion of Tuple Syntax
bearophile
bearophileHUGS at lycos.com
Wed Aug 21 10:40:51 PDT 2013
Andrei Alexandrescu:
> The current language would be D as it is today, with no
> syntactic addition.
Right.
> So I guess that would be:
>
> a.
> alias Types = TypeTuple!(int, long);
> auto values = tuple(1, "str");
> b.
> auto a = tup[0];
> auto b = tup[1];
> tup.scatter(a, b);
>
> "scatter" is not defined yet. It scatters the content of a
> tuple over the (ref-passed) arguments.
OK.
But there are five missing useful sub-features, that I have
listed in my answer:
c. unpacking tuples in function signatures;
zip(arr1, arr2).map!(ab => ab[0] * ab[1]);
["a", "b"].emumerate.map!(js => js[1].replicate(js[0]));
(enumerate is a simple but very useful range not yet present in
std.range that yields index-item pairs).
d. unpacking tuples in foreach loops;
foreach (xy; zip(arr1, arr2)) {
// uses xy[0]
// uses xy[1]
}
e. unpacking tuples in switch cases;
auto tup = tuple(10, 20);
if (tup[0] == 0 && tup[1] == 10) {...
} else if (tup[0] == 0) { ...
} else { ... }
f. unpacking small arrays.
auto a = [10, 20];
const x = a[0];
const y = a[1];
g. wildcards (usable in every other a-f case);
auto a = tup[0];
// skipped second tuple item
auto c = tup[2];
In some cases you have to use: _1, _2, or _ and __, etc.
Bye,
bearophile
More information about the Digitalmars-d
mailing list