DIP9 -- Redo toString API
Don
nospam at nospam.com
Mon Nov 22 03:42:22 PST 2010
spir wrote:
> On Mon, 22 Nov 2010 10:14:03 +0100
> Don <nospam at nospam.com> wrote:
>
>> Tomek Sowiński wrote:
>>> Don <nospam at nospam.com> napisał(a):
>>>
>>>> The efficiency issues are important, but are not the primary motivation.
>>>> toString() is just wrong. The idea that there is ONE AND ONLY ONE
>>>> textual representation of an object, is, frankly, idiotic.
>>> I always thought of toString() as an aid in debugging, where having one
>>> and only way to print out an object makes sense.
>> It isn't just used in debugging. It's used for writefln.
>> But even for debugging, it doesn't work.
>>
>> If I have a struct:
>>
>> struct Foo
>> {
>> Complex!(double) val;
>> }
>>
>> and, for debugging purposes, I want to write 'val' to 10 decimal places.
>> How do I do that?
>
> I agree with you. toString lacks flexibility in some (not very common but relevant) cases, that would be brought by an optional format specifier. I would enjoy beeing able to write this with toString, instead of a custom text() method:
>
> struct Complex {
> float r,i;
> string text(string numberFormat="%.3f") {
> string outFormat = format("%s+%sj", numberFormat,numberFormat);
> return format(outFormat, this.r,this.i);
> }
> }
> void main () {
> auto c = Complex(1.11111,3.333333333);
> writeln(c.text());
> writeln(c.text("%.7f"));
> }
> ==>
> 1.111+3.333j
> 1.1111100+3.3333333j
>
>
> But, to be fair, does this have anything to do with the current <writeTo vs toString> debate?
> The only actual point of said debate is efficiency.
The debate was triggered by me saying (in Bugzilla) that BigInt would
not provide a parameterless toString(), because I can't implement it.
Instead, in BigInt, I provided a function:
void toString( void delegate(const(char)[]) sink, string format);
which solves the formatting issue, as well as the performance issue.
I'm certainly open to other ways of solving the problem. But
string toString();
doesn't seem adequate for the task.
More information about the Digitalmars-d
mailing list