The state of string interpolation
Sebastiaan Koppe
mail at skoppe.eu
Fri Dec 7 10:26:29 UTC 2018
On Thursday, 6 December 2018 at 22:31:07 UTC, Jonathan Marler
wrote:
> There's a reason why there's no way to access the callers scope
> without a mixin...because it breaks encapsulation. Imagine
> this:
>
> int x = 10;
> foo();
>
> What is the value of x after this? If a function (or whatever
> foo is) could access the caller's scope, then it could be
> anything.
I agree, it is thin ice. But Mike asked for a generalisation and
this is it.
Also, scala's implicit parameters do also allow mutation.
Although in scala stuff is generally immutable to begin with.
> Interpolated strings are a special case because even though
> they can access the caller's scope, they do this explicitly:
>
> int x = 10;
> foo(i"$(x=20)");
>
> You can clearly see that x is being set to 20, you don't need
> to know the implementation specifics of interpolated strings to
> see that.
Good point.
> On that note, you could make an argument that you should be
> able to access the caller's state in a "read-only" capacity,
I was about to say that.
> but that can get complicated. Say you have this:
>
> int x = 10;
> int* y = &x;
> foo();
>
> What's the value of x after this? What if we define foo as:
>
> void foo(CallerScope s = __CALLER_SCOPE__)
> {
> *(cast(int*)s.y) = 20;
> }
>
> We did have to cast `y` from const(int*) to int*, but we were
> able to change x nonetheless. You end up with the same problem
> that you have to understand every function you call at a much
> deeper level to know when it can modify your local state.
Same problem indeed, but one with a lower probability.
Still thin ice, for sure. But I have to say a small part of me
likes it (besides enabling string interpolation, it would also
enable things like 'importing' user defined functions in a
library without explicitly passing them via a template parameter.)
More information about the Digitalmars-d
mailing list