The state of string interpolation
Steven Schveighoffer
schveiguy at gmail.com
Thu Dec 6 22:24:50 UTC 2018
On 12/6/18 5:03 PM, o wrote:
> I agree that lowering to a tuple opens up some cool possibilities, but
> what about the times when it is desired to just use string interpolation
> as just a plain string?
> For example, if `i"a is ${a}."` is equivalent to 'tuple("a is ", a,
> ".")', then if you want to use the interpolated string as a string, you
> would have to do something like `text(i"a is ${a}.")`. If this is the
> case, how much better is this over a library implementation, which would
> look like this: `interp!"a is ${a}."`?
`text(...)` is the way to go. Or rather `i"a is $a".text`;
And no, it wouldn't be interp!"a is $a.", as you HAVE to put mixin in
there (this is how scriptlike works).
Consider if you are actually writing a string interpolation to do a
mixin, it would be:
mixin(mixin(interp!"..."));
>
> I am definitely not saying that a library solution is a better idea. I
> personally think that this only makes sense as a language feature. But I
> just think it would be best if `i"a is ${a}"` is more or less equivalent
> to `"a is "~a.to!string~"."`.
I get what you are saying. But this solution is inferior for a few reasons:
1. It allocates. Maybe many times (lots of to!string calls allocate).
2. It loses information.
3. It depends on a library feature (i.e. unusable in betterC).
> As you said, string interpolation is just (very nice) syntactic sugar
> over concatenation, so I think we should make this sugar as sweet as
> possible.
It's sugar, but I'd prefer it to be D-flavored sugar. Expose what the
developer wrote at compile-time, and let the language gurus work their
magic. Concatenation is accessible, easily, but so are so many other
things that make this very useful.
D is capable of doing so much, because of the ability to introspect, and
discover at compile-time. I'm still freaking amazed that vibe.d can take
a line like:
render!("myview.dt", foo, bar);
and process a DSL which has access to foo and bar, by those names, and
outputs a compiled D function. I want to allow enabling such things with
string interpolation too.
-Steve
More information about the Digitalmars-d
mailing list