On 08/31/2011 11:00 PM, Paul D. Anderson wrote:
Paul D. Anderson Wrote:
Can someone clarify for me the status and/or direction of string formatting in
D?
We've got:
1. toString, the object method with no parameters.
2. toString(sink, format)
3. to!String()
4. format
5. writef/writefln
6. write/writeln
I realize these exist for various reasons, some (1,3) are simple (unformatted)
conversions, others (2,4-6) are designed to provide configurable formatting.
The problem is that they are inconsistent with each other.
Using std.bigint as an example: 1, 3, 4 and 6 don't work, or don't work as
expected (to me at least). 1. prints 'BigInt', 3 and 4 are compile errors.
I know bigint is a controversial example because Don has strong feelings
against 1 and favors 2. (See bug #5231). I don't really have an opinion one way
or the other but I need to know what to implement in my arbitrary-precision
floating point module. This obviously relies heavily on bigint.
So, is there a transition underway in the language (or just Phobos) from
toString, writeln and format, to toString(sink,format) and writefln?
Or is this just a divergence of views, both of which are acceptable and we'll
have to get used to choosing one or the other?
Or am I just mistaken in believing there is any significant conflict?
I apologize if this has already been hashed out in the past and, if so, I would
appreciate someone pointing me to that discussion. (Or just the results of the
discussion.)
Paul
So, IIUC, toString has its faults but it has deep-rooted user expectations,
while toString(sink, format) [or writeTo(sink, format)] is a better
implementation, but the current state of development doesn't have a lot of
support for it.
With respect to the Java implementation: they provide the two number-to-string
functions called out in the specification, i.e., toScientificString and
toEngineeringString and use the toScientificString method as the default
toString. One of the big advantages of doing this is that the read and write
routines are complementary -- writing out a number and reading it back in
results in not just the same value, but the same internal representation. (This
is one of the goals of the specification.)
Based on this, my proposal for the BigDecimal type is to provide similar
functionality -- the two functions listed above, with the first being called by
the toString function. In addition the toString(sink, format) function will be
provided, and/or whatever it takes to work with format and writef.
I poked around a little in the std.stdio and std.format source code and I see
that stdio.writef calls std.format.formattedWrite, so anything that works for
the one should work for the other.
I don't know what is required to make to!string work but that is a discussion
for another day.
Please advise if I've misunderstood.
I think your approach is what std.bigint should do too. Great!
to!string will already work, because you provide the toString() member
function.