digitalmars.D.bugs - [Issue 9817] New: Syntax change for front tuple expansion in foreach
- d-bugmail puremagic.com (80/80) Mar 26 2013 http://d.puremagic.com/issues/show_bug.cgi?id=9817
http://d.puremagic.com/issues/show_bug.cgi?id=9817 Summary: Syntax change for front tuple expansion in foreach Product: D Version: D2 Platform: All OS/Version: All Status: NEW Severity: normal Priority: P2 Component: DMD AssignedTo: nobody puremagic.com ReportedBy: bearophile_hugs eml.cc I have tagged this as bug report instead of as enhancement request. This program shows that D foreach is able to "unpack" tuples that are produced by a range: import std.algorithm: group; void main() { auto data = ['a', 'a', 'b', 'b']; foreach (c, n; group(data)) { pragma(msg, typeof(c)); pragma(msg, typeof(n)); } } It prints: dchar uint This feature is mostly undocumented: http://d.puremagic.com/issues/show_bug.cgi?id=7361 But this feature doesn't work with an array of tuples (because it clashes against a precedent semantics of foreach, that assigns the first variable to the indexes of the array): import std.typecons: tuple; void main() { auto data = [tuple("red", 10), tuple("blue", 20)]; foreach (x, y; data) { pragma(msg, typeof(x)); pragma(msg, typeof(y)); } } It prints: uint Tuple!(string, int) In this thread (and on Bugzilla) I have suggested to add unpacking syntax in various situations: http://forum.dlang.org/post/gridjorxqlpoytuxwpsg forum.dlang.org I think the fully transparent unpacking syntax as in "foreach(c,n; group(data))" is rigid (there is no way to tell if you want the first variable to be bound to the array index, or to the first item of the tuple) and not sufficiently explicit. So I propose to replace the current syntax that unpacks tuples with a different and explicit syntax that removed ambiguities, is more flexible, and works with both arrays and ranges: import std.algorithm: group; import std.typecons: tuple; void main() { auto data1 = ['a', 'a', 'b', 'b']; foreach ((c, n); group(data1)) {} auto data2 = [tuple("red", 10), tuple("blue", 20)]; foreach ((s, n); data2) {} foreach (i, tup; data2) {} foreach (i, (s, n); data2) {} } This syntax is meant to be usable in other situations, so it must be designed thinking about the future too: import std.typecons: tuple; void foo((string s, int b)) {} void main() { foo(tuple("red", 10)); auto (a, b) = tuple("red", 10); auto t = tuple("red", 10); switch (t) { case (a, b): break; default: } } Other syntaxes are possible. -- Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email ------- You are receiving this mail because: -------
Mar 26 2013