Bug 6521 – writeln(const(tuple)) doesn't show the field values
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2011-08-17T07:49:00Z
Last change time
2011-09-09T08:03:36Z
Assigned to
nobody
Creator
bearophile_hugs
Comments
Comment #0 by bearophile_hugs — 2011-08-17T07:49:07Z
import std.stdio: writeln;
import std.typecons: tuple;
void main() {
auto r1 = tuple(1);
writeln(r1);
const r2 = tuple(1);
writeln(r2);
}
2.055beta prints:
Tuple!(int)(1)
const(Tuple!(int))
But I'd like to see the values of the fields (1) in the second case too.
Comment #1 by k.hara.pg — 2011-08-17T18:15:36Z
Expected prints:
Tuple!(int)(1)
const(Tuple!(int))(1)
There are two ways to fix the problem.
1. Change std.typecons.Tuple!T.toString like follows:
diff --git a/std/typecons.d b/std/typecons.d
index b279abf..b80d6f9 100644
--- a/std/typecons.d
+++ b/std/typecons.d
@@ -491,9 +491,9 @@ assert(s[0] == "abc" && s[1] == 4.5);
/**
Converts to string.
*/
- string toString()
+ const string toString(this T)()
{
- enum header = typeof(this).stringof ~ "(",
+ enum header = T.stringof ~ "(",
footer = ")",
separator = ", ";
Appender!string app;
But this is very hackish to me.
2. Apply my pull request
https://github.com/D-Programming-Language/phobos/pull/126
This patch changes formattedWrite behavior: if a struct type does not have toString method, formattedWrite formats it like POD (e.g. "TypeName(field, ...)").
I think that Tuple is just a POD type, and expected formatting also looks like the POD.
So, IMHO, std.typecons.Tuple!T.toString is *just a workaround*.
If formattedWrite works correctly, we will no longer need Tuple!T.toString.
Comment #2 by bearophile_hugs — 2011-08-17T19:49:15Z
(In reply to comment #1)
> There are two ways to fix the problem.
>
> 1. Change std.typecons.Tuple!T.toString like follows:
> 2. Apply my pull request
> So, IMHO, std.typecons.Tuple!T.toString is *just a workaround*.
> If formattedWrite works correctly, we will no longer need Tuple!T.toString.
I agree that the point 2 is better.
Your Phobos pull 126 looks exceptionally good, it seems to solve most problems I have with D printing since years. Thank you very much for it.
-----------------
But I have one more note. Producing a good print is a matter of balances and tradeoffs. When I print many tuples that contain several fields (with field names too), the output is currently very noisy and very long. I see some alternative solutions to this problem:
1) Keep things as in you pull 126. So every tuple gets printed like:
Tuple!(int, "x", double, "dx")(1, 1.5)
2) Use a shorter textual representation for tuples, that shows no types and no field names. Example:
tuple(1, 1.5)
Or even just:
(1, 1.5)
3) Find some intermediate way. Example: print single tuples fully:
Tuple!(int, "x", double, "dx")(1, 1.5)
but print arrays of tuples in a more compact way:
[tuple(1, 1.5), tuple(2, 2.5)]