String interpolation
mw
mingwu at gmail.com
Wed May 20 23:41:15 UTC 2020
On Tuesday, 10 November 2015 at 13:36:44 UTC, Andrea Fontana
wrote:
> On Tuesday, 10 November 2015 at 12:40:07 UTC, Márcio Martins
> wrote:
>> writeln(interp!"The number #{a} is less than #{b}");
>>
>> Quite pleasant syntax this way :)
>> Not sure if it's feasible to do this on the language side.
>
> Yes. Here a (stupid!) proof of concept:
> http://dpaste.dzfl.pl/74b1a4e3c8c6
$ cat i.d
---------------------------------------------------------------------
import std.stdio;
template interp(X) {
alias interp = mixin(interpGenCode!X);
}
void main() {
int a = 10;
int b = 20;
writeln(mixin(interp!"The number #{a} is less than #{b}"));
writeln(interp!"The number #{a} is less than #{b}");
}
---------------------------------------------------------------------
$ dmd.exe i.d
i.d(10): Error: template instance interp!"The number #{a} is less
than #{b}" does not match template declaration interp(X)
i.d(11): Error: template instance interp!"The number #{a} is less
than #{b}" does not match template declaration interp(X)
I'm wondering if this code has once worked? and seems
dpaste.dzfl.pl no longer there.
Can we do string interpolation in D now?
Speaking of language evolution in the other thread,
C# has string interpolation now, here:
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
string name = "Mark";
var date = DateTime.Now;
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek},
it's {date:HH:mm} now.");
Python have it here:
https://www.python.org/dev/peps/pep-0498/
>>> import datetime
>>> name = 'Fred'
>>> age = 50
>>> anniversary = datetime.date(1991, 10, 12)
>>> f'My name is {name}, my age next year is {age+1}, my
>>> anniversary is {anniversary:%A, %B %d, %Y}.'
'My name is Fred, my age next year is 51, my anniversary is
Saturday, October 12, 1991.'
>>> f'He said his name is {name!r}.'
"He said his name is 'Fred'."
How can we do it in D? or when will we have it :-)?
More information about the Digitalmars-d-learn
mailing list