writef, positional arguments, and array formatting

bearophile bearophileHUGS at lycos.com
Thu Oct 9 09:34:00 PDT 2008


Andrei Alexandrescu:
> 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

The need to format single items of an array isn't so much common, but it's common enough to be an interesting case. I may be better to reduce the complexity of your idea: you can specify just the type of the bottom level of the given _collection_, and you can't specify the separator. It's less flexible, but I think it covers most of the common situations. So the syntax becomes the following in both cases:

%(s)

A syntax like %(s:s) may be used to specify how to format the bottom levels of associative arrays :-)

Bye,
bearophile



More information about the Digitalmars-d mailing list