Discussion Thread: DIP 1036--Formatted String Tuple Literals--Community Review Round 1

Adam D. Ruppe destructionator at gmail.com
Wed Sep 9 23:47:35 UTC 2020

On Wednesday, 9 September 2020 at 23:04:37 UTC, James Blachly 
> Are there contemporary examples of other languages whose string 
> interpolation is as complex as this proposals? I am really only 
> most familiar with Javascript and Python, both of which use 
> automatic memory management and the *string is a string is a 
> string*.

Javascript is actually *very* similar to this dip, with the key 
difference that in D, we reuse existing normal function call 
syntax whereas Javascript invented a new magic function call 
syntax just for this feature.

See the "Tagged templates" section here: 

Notice that they call it a "template literal" rather than an 
interpolated string since it is so much more than a string.

If you write

foo`${5}, ${23}`

in Javascript, it actually will rewrite that into a function call:

foo([ "", ", ", ", ", "" ], 5, 23);

I realize that's hard to read with all the quotes and commas... 
but it is essentially a dynamically-typed equivalent to what this 
DIP is talking about.

The first argument to foo is a string spec. In D, we represent it 
as a templated struct. Javascript instead represents that as an 
array of strings. But it is fundamentally the same idea: it gives 
the string pieces from around the placeholders and an entry 
representing the inserted item.

Then, the interpolated items are passed as separate arguments 
after the spec - just like we propose for D. The example on MDN 
for this uses JS' `...values` syntax to put it into an array, in 
D, we'd call that same thing `(Values...)(Values values)`, but 
again it is the same thing, just JS uses their dynamic typing 
whereas D uses a template.

Now, the obvious difference with Javascript is they have a 
default function. Above, I wrote foo`...`. Leave the foo part off 
and it uses the default function instead - which is identical to 
our proposed idup. JS can do this because they introduced a new 
function call syntax to the language. And they can do that 
because JS only has one kind of function call to begin with: 
obj.foo(x) (where obj is optional and will default to null).

D, by contrast, has several kinds of function calls: traditional 
foo(x), UFCS x.foo, and template foo!(x). Instead of inventing 
three new kinds of magic function call syntax, we just reuse what 
we already have. But, of course, that does have one small 
downside: there's no way to insert a default function like 
Javascript does without either more compiler magic or limiting it 
to just one case and forgetting about the others.

Instead we simply ask you to explicitly call the function you 
want in all cases. I doubt most users will even find this 
particular controversial after they try it in reality.

More information about the Digitalmars-d mailing list