DIP 1027---String Interpolation---Community Review Round 1
Patrick Schluter
Patrick.Schluter at bbox.fr
Tue Dec 17 10:14:35 UTC 2019
On Tuesday, 17 December 2019 at 09:20:06 UTC, Jacob Carlborg
wrote:
> On Monday, 16 December 2019 at 12:55:17 UTC, Patrick Schluter
> wrote:
>
>> Yes, probably. The issue I had with the transformation as
>> string is what should the code below print?
>>
>> import fn;
>>
>> int a, b = 20;
>>
>> string inter = i"$(a+b)";
>>
>> for(a=0; a<10; a++)
>> fn(inter);
>>
>> ---
>> module fn;
>>
>> void fn(string s)
>> {
>> writef(s);
>> }
>>
>> prints
>> 202020202020202020
>>
>> or
>>
>> 212223242526272829
>>
>> and that's the difference between CT evaluation and RT
>> evaluation.
>
> It's difficult to say as your code doesn't compile. As it's
> written the code will fail to compile because you cannot have a
> for-loop at module scope. The line where `inter` is declared
> would fail to compile as well because `a` and `b` cannot be
> read at compile time. I don't see how that would be any
> different compared to this code:
>
> module foo;
> int a, b = 20;
> int c = a + b; // fails to compile as well
>
> If all of this code would be wrapped in a function, then it
> would successfully compile. `inter` would be evaluated to "20"
> and the code would print:
>
> 20202020202020202020
>
> I don't see how it would behave any differently than if you
> replaced `string` with `int` and removed `i"$"`.
>
> For the result to be `212223242526272829` `i"$(a+b)"` would
> need to be a macro.
>
Yes, and that was the point of the exercice. Transforming the
interpolated "string" into a string evaluates the values of the
variables at the moment of that transformation. From then on,
there is no interpolation possible as it a simple string.
I suppose that what aliak leant in his comments was that the
string then could still be used for interpolation.
hypothetic scenario of what I interpreted what aliak wanted (and
it won't compile, it's just for illustration)
int apple;
...
string my_is = i"apple=${apple}";
...
apple = 36;
writeln(my_is);
would print "apple=36"
with this DIP, when you do this
int apple;
...
string my_is = i"apple=${apple}".format;
...
apple = 36;
writeln(my_is);
will print "apple=0" because my_is will contain the string
"apple=0"
The basic thing here is what Walter said above:
interpolated strings are not string literals, they can't be. They
are code.
More information about the Digitalmars-d
mailing list