D rawkz! -- custom writefln formats
H. S. Teoh
hsteoh at quickfur.ath.cx
Thu Jan 17 11:18:18 PST 2013
On Thu, Jan 17, 2013 at 07:12:56PM +0100, Andrej Mitrovic wrote:
> On 1/16/13, H. S. Teoh <hsteoh at quickfur.ath.cx> wrote:
> > // Wait -- what? What on earth are %i, %j, %k, and %l?!
> > writeln("%i", s); // Hmm, prints "i"!
> > writeln("%j", s); // Hmm, prints "j"!
>
> I wish we could write string specifiers rather than char specifiers.
> You can invent your own char specifiers but they're still going to be
> hard to understand at the call site. I would prefer:
>
> > writefln("{fullname}", s);
> > writefln("{type}", s);
>
> And have:
>
> void toString(scope void delegate(const(char)[]) sink,
> FormatSpec!string fmt) const
> {
> switch(fmt.spec)
> {
> case "fullname"
> break;
> case "type":
> break;
> }
> }
>
> We could invent this in our own library but it won't be usable with
> existing format and write functions.
What would *really* be nice is if we extended the current format
specifiers to be able to deal with named parameters and custom
modifiers, for example:
struct Actor {
string name;
void toString(scope void delegate(const(char)[]) sink,
FormatSpec!string fmt) const
{
switch (fmt.spec)
{
case "thename":
sink("the ");
sink(name);
break;
case "Thename":
sink("The ");
sink(name);
break;
case "name":
sink(name);
break;
case "Name":
assert(name.length > 0);
sink(toUpper(name[0]));
if (name.length > 1)
sink(name[1..$]);
break;
default:
...
}
}
}
auto x = Actor("man");
auto y = Actor("dog");
auto z = Actor("cats");
writeln("%{subj:Thename} is feeding %{obj:thename}.", [
"subj": x,
"obj": y
]);
// Outputs: "The man is feeding the dog."
writeln("%{subj:Name} don't like %{obj:thename}.", [
"subj": z,
"obj": x
]);
// Outputs: "Cats don't like the man."
writeln("But %{subj:thename} likes %{obj:name}.", [
"subj": y,
"obj": z
]);
// Outputs: "But the dog likes cats."
T
--
A mathematician is a device for turning coffee into theorems. -- P. Erdos
More information about the Digitalmars-d
mailing list