String Interpolation

Arafel er.krali at gmail.com
Mon Oct 30 18:18:30 UTC 2023


On 30/10/23 18:37, Adam D Ruppe wrote:
> On Monday, 30 October 2023 at 17:26:27 UTC, IGotD- wrote:
>> Thank you for this and alias this wasn't even on my mind. We need more 
>> posts like this, solutions and how to move forward.
> 
> This considered in my original proposal, 4 1/2 years ago:
> http://dpldocs.info/this-week-in-d/Blog.Posted_2019_05_13.html#my-string-interpolation-proposal

Yes, I think I read it at the time, and it probably has unconsciously 
shaped my ideas, as have DIP1036 and YAIDIP (these two consciously).

Anyway, I went ahead and implemented a proof of concept, using mixins:

https://gist.github.com/erkrali/d48ed754b68a26e326b61aad78d43ab7

There's no documentation, but the code and unit tests should be quite 
clear. In short:

```d
foo (string s) { }
formatedFoo(IS)(IS is) if (isInterpolatedString!IS) {
	// Advanced formatting here
}

auto message = mixin(i!`Hello, $(name). Your balance is 
$({%f1.3}balance).`);
foo(message); // Works
formatedFoo(message): // Also works
```

The formatting part is optional and ignored in the default `toString` 
implementation, but still made available for libraries. The original 
strings representing the interpolated expressions are also made available.

Pros:

* Intrinsic cast to string.
* Can get a tuple to be used in `text` (shorthand: `mixin(it!"Hello, 
$(name)");`.
* In the struct you get all the existing information: The "static" text, 
the format string, the original symbol, and the value to interpolate.
* Can do overloads that unlock more advanced processing.
* Functions can choose whether to support only the advanced processing.
* It should be possible to use in -betterC as long as `toString` is not 
called, i.e. as long as only the `struct` or the `tuple` are used.

Cons:

* Well, it's a mixin. But that's just to show how it could look like.
* It's tied to `std.conv : to` for the default string conversion.
* The parsing probably stinks, has bugs, and is inefficient as hell. It 
could also eat your kittens. I'd assume that a "proper" implementation 
would be much better, but I don't have that much experience (if any at 
all) in this area.

So, all in all, it's just a proof-of-concept to show that it can really 
be done, and it's not just theory.


More information about the Digitalmars-d mailing list