[Issue 4579] New: std.typecons.Tuple syntax unpacking sugar
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Tue Aug 3 17:13:19 PDT 2010
http://d.puremagic.com/issues/show_bug.cgi?id=4579
Summary: std.typecons.Tuple syntax unpacking sugar
Product: D
Version: D2
Platform: All
OS/Version: All
Status: NEW
Severity: enhancement
Priority: P2
Component: DMD
AssignedTo: nobody at puremagic.com
ReportedBy: bearophile_hugs at eml.cc
--- Comment #0 from bearophile_hugs at eml.cc 2010-08-03 17:13:16 PDT ---
In this enhancement request I propose to add syntax sugar to D2 that allows to
"unpack" std.typecons.Tuple at the calling point.
This enhancement request doesn't ask for a third new kind of tuple, the normal
std.typecons.Tuple Phobos2 one is enough.
Essentially std.typecons.Tuple can be used to have multiple return values in D,
but some syntax sugar helps.
In Python2.x language, that is able to return tuples too, this automatic tuple
unpacking is _very_ common and very handy (D makes this situation a little
different, because std.typecons.Tuple supports named fields, and fields are
statically typed):
def sqr_cube(x):
return x*x, x*x*x
x2, x3 = sqr_cube(10)
(Python2.x also allows nested tuple unpacking with a bit of pattern matching,
and Python3.x allows "variable length" unpacking with the * syntax.)
This is a function of std.file (Phobos2 of DMD 2.047):
void getTimes(in char[] name, out d_time ftc, out d_time fta, out d_time ftm);
Introducing tuples more into Phobos its signature becomes:
Tuple!(d_time "ftc", d_time "fta", d_time "ftm") getTimes(const string name);
But then you have to use it for example like this:
void main() {
auto t3 = getTimes("filename");
with(t3) {
writeln(ftc, " ", fta, " ", ftm);
}
}
While adding a bit of syntax sugar to D it becomes:
void main() {
// Here I have used "fc" != "ftc"
(d_time fc, d_time fa, d_time fm) = getTimes("filename");
}
That syntax sugar means something like:
void main() {
auto __temp1 = getTimes("filename");
d_time fc = __temp1.field[0];
d_time fa = __temp1.field[1];
d_time fm = __temp1.field[2];
}
I think that sugar doesn't clash with C syntax, so this syntax doesn't
introduce bugs when porting code from C to D. This new syntax looks natural
enough to me, and handy in high-level-style D programming.
Nested unpacking too is a possibility:
(int x, (int y, int z)) = foo();
See also bug 4577 for Tuples.
--
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
More information about the Digitalmars-d-bugs
mailing list