writef, positional arguments, and array formatting

Steven Schveighoffer schveiguy at yahoo.com
Thu Oct 9 08:26:49 PDT 2008


"Andrei Alexandrescu" wrote
>I don't want to divert anyone's attention from more important issues, but 
>I'm running into a few little problems here with writef and friends.
>
> 1. Printing only some arguments
>
> Currently writef insist on formatting all arguments, even those that don't 
> have a format spec allocated. This creates problem in an app of mine that 
> takes a format string as a command-line argument and selectively prints 
> stuff. For example:
>
> ./kernelize --format='%1$s %2$s'
>
> The call is:
>
> uint id1, id2;
> float value;
> ...
> writefln(format, id1, id2, value);
>
> I need:
>
> 12 23
>
> But instead I get:
>
> 12 230.34
>
> I wonder how this could be addressed. Should presence of positional 
> parameters suppress the "print'em all" approach?

It is this way in Tango AFAIK.  You could write a wrapper for it (in 
pseudocode):

writefln2(string format, ...)
{
   x = count % in format;
   return writefln(format, varargs[0..x]);
}

>
> 2. Formatting arrays
>
> This has been an ongoing problem with formatting functions: there's no 
> proper formatting for arrays beyound writing %s and formatting the entire 
> array with [e0 e1 ... en]. I was thinking of improving that like this:
>
> int[] a = [ 42, 1, 2 ];
> writefln("%(s, )", a); // prints "42, 1, 2"
>
> "%(" opens a spec that will be applied to each element of the array. For 
> the last element, only the format part of the spec applies, not the 
> trailing string (in the example above ", "). One nice thing is that the 
> specs can be nested, so:
>
> int[][] a = [ [ 42, 1, 2 ], [ 3, 4 ] ];
> writefln("%((s, )\n)", a); // prints "42, 1, 2"
>
> will print:
>
> 42, 1, 2
> 3, 4
>
> that is, one subarray per line with elements separated with commas and 
> spaces.
>
> Is this something you'd use?

That is a very good idea!  Tango is the same way, in fact, tango got ability 
to print arrays fairly recently.  If I used Phobos, I'd certainly use it. 
How many times I wanted to print an array of ints as hexadecimal, but was 
forced to do some stupid loop thing...

I'll propose something similar on Tango as well.

-Steve 





More information about the Digitalmars-d mailing list