Interpolated strings

Jonathan Marler via Digitalmars-d digitalmars-d at puremagic.com
Tue Apr 18 14:56:28 PDT 2017


On Tuesday, 18 April 2017 at 08:50:07 UTC, Walter Bright wrote:
> On 4/15/2017 4:51 PM, cym13 wrote:
>> Removing imports is a good point, the first concrete one to be 
>> mentionned. I'm
>> not sure it matters that much though as I think those imports 
>> are generic enough
>> that I believe they would be imported anyway, but it's a real 
>> point.
>
> It may not be necessary to have any dependencies on any import.
>
>     $"{a} times 3 is {a*3}"
>
> could be rewritten by the parser to:
>
>     "%s times 3 is %s", a, a * 3
>
> and that is that. (I.e. just an AST rewrite.) It would be quite 
> a bit simpler than Jonas' proposed implementation.

I've thought about it and decided, I like this idea.  I've only 
used interpolated strings in PHP which left a bad taste, but I 
realized that interpolating strings makes it impossible for your 
format string and your arguments to get out of sync. This makes 
interpolated strings harder to use incorrectly (Scott Meyers had 
a good talk on this, https://www.youtube.com/watch?v=5tg1ONG18H8).

The biggest drawback I could think of was overhead, but with an 
implementation like this there is NO RUNTIME OVERHEAD!  It's also 
simple (easy to implement and understand) and flexible (works 
with all existing functions that accept "format-like" arguments).

Have you thought about supporting format specifiers as well?  I 
looked at the C# version and it looks like they can specify them 
using a colon like this:

     $"{a} in hex is {a:x}"

However this may create an ambiguity in the grammar, not sure. 
I'm not sure what kind of expression would be supported in the 
braces.  If the expression supported labels then this would 
definitely cause ambiguity.  In the example "{a:x}", the symbol 
"a" could just be parsed as a label.


More information about the Digitalmars-d mailing list