[phobos] phobos commit, revision 1748

Andrei Alexandrescu andrei at erdani.com
Mon Jul 12 06:33:02 PDT 2010


On 07/12/2010 03:04 AM, Lars Tandle Kyllingstad wrote:
> (Sorry, sent this to Andrei's private address.  Resending to list.)
>
> That sounds like a good idea.  Should fmt include the '%' character of
> the format specifier?

I'd think so. Also, types could define their own format specifiers if 
they want to.

BTW I've changed the grammar of the format specifiers to allow unlimited 
nesting. A format string may contain a nested format string by enclosing 
it in %( and %). The intent is to print elaborate types comfortably. For 
example, this:

int[string] a = ["abc":1, "def":5];
writefln("Here's the map:\n"
     "%(=== %2$ is mapped by %1$ ===\n%) ===\n\nThat was it", a);

produces:

Here's the map:
=== 1 is mapped by abc ===
=== 2 is mapped by def ===

(I've also showcased positional parameters.) Note how the nested 
specifier is used for each <key,value> pair in the map. The last time 
around the trailing specifier is not printed in order to allow e.g. 
printing arrays without a trailing comma. This time I did want the 
trailing portion to be present for the last element, so I added it after 
the nested specifier.

The format string above is parsed correctly but the current version 
doesn't support associative arrays yet.

Now getting back to types defining their own format specifiers, for 
example Data could define its own spec that understands %D, %M, and %Y. 
Then you could print stuff like this:

Date d;
double x;
writefln("I paid $%g on %(%M/%D/%Y%)", x, d);

producing:

I paid $5 on 07/12/2010

The nested specifier is passed to Date's toString function along with a 
delegate that writes to the standard output.


Andrei


More information about the phobos mailing list