DIP 1027---String Interpolation---Community Review Round 1
mipri
mipri at minimaltype.com
Fri Dec 13 00:05:54 UTC 2019
On Thursday, 12 December 2019 at 23:31:21 UTC, Petar Kirov
[ZombineDev] wrote:
> On Thursday, 12 December 2019 at 17:03:53 UTC, Atila Neves
> wrote:
>>
>> It'd be great if you could expand on this with a list of
>> examples of what D could do.
>
> Tagged template literals are indeed quite nice in JS. Here's an
> example from the chalk npm package [1]:
>
> ```js
> // Plain template literals (a.k.a. built-in string
> interpolation):
> const str1 = `
> CPU: ${chalk.red("90%")}
> RAM: ${chalk.green("40%")}
> DISK: ${chalk.yellow("70%")}
> `;
With no changes to DIP-1027:
const str1 = format(i"
CPU: %(chalk.red("90%"))
RAM: %(chalk.green("40%"))
DISK: %(chalk.yellow("70%"))
");
which lowers to
const str1 = format("
CPU: %s
RAM: %s
DISK: %s
", chalk.red("90%"), chalk.green("40%"), chalk.yellow("70%"));
> // Same example but with tagged template literals - more DRY:
> const str2 = chalk`
> CPU: {red 90%}
> RAM: {green 40%}
> DISK: {yellow 70%}
> `;
Likewise:
with (chalk) {
const str2 = format(i"
CPU: %(90.percent.red)
RAM: %(40.percent.green)
DISK: %(70.percent.yellow)
");
}
> // Tagged template literals + interpolation of variables:
> const cpu = 90;
> const ram = 40;
> const disk = 70;
>
> const str3 = chalk`
> CPU: {red ${cpu}%}
> RAM: {green ${ram}%}
> DISK: {yellow ${disk}%}
> `;
Likewise:
with (chalk) {
const str2 = format(i"
CPU: %(cpu.red)
RAM: %(ram.green)
DISK: %(disk.yellow)
");
}
> Here's another example, this case from the es2015-i18n-tag
> library [2] that applies translations, locale and currency
> formatting:
>
> const name = 'Steffen'
> const amount = 1250.33
> console.log(i18n`Hello ${ name }, you have ${ amount }:c in
> your bank account.`)
> // Hallo Steffen, Sie haben US$ 1,250.33 auf Ihrem Bankkonto.
> ```
Likewise:
writeln(i18n(i"Hello %name, you have %{$}(amount) in your bank
account."));
which lowers to:
writeln(i18n("Hello %s, you have %$ in your bank account.",
name, amount));
and normal function i18n can do the gettext() stuff, and handle
%$ itself, or indeed it could do nothing special with %$ but
leave it to custom format specifiers and `amount` being a
monetary object:
https://wiki.dlang.org/Defining_custom_print_format_specifiers
So I must conclude:
1. This is all very cool, but
2. DIP-1027 can do all of it as currently specified.
3. Actually DIP-1027 is not as bad as I thought. In particular,
instead of documenting the feature in terms of its failures vs.
other languages, it can say "use format() if you mainly to
build a string" and "here's some cool stuff that this design
lets you do, that more traditional string interpolation could
not do."
So I respectfully withdraw my complaints and instead submit
support for some kind of SQL generalization with ?
placeholders.
More information about the Digitalmars-d
mailing list