Emulation macros and pattern matching on D

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 5 07:23:15 PDT 2015


On 6/5/15 10:15 AM, Dennis Ritchie wrote:
> On Friday, 5 June 2015 at 13:13:15 UTC, Steven Schveighoffer wrote:
>> string foo(string mode, string value)
>> {
>>    return `writefln("mode ` ~ mode ~ `: %s", ` ~ value ~ `);`;
>> }
>>
>> void main()
>> {
>>    mixin(foo("Y", "3"));
>>    mixin(foo("X", "2"));
>> }
>
> Thanks. It looks really simple, but I still do not understand the
> concept of using mixins in full.
>
> I do not understand why in this line:
> return `writefln("mode ` ~ mode ~ `: %s", ` ~ value ~ `);`;
>
> use the following syntax:
> ~ mode ~ , ~ value ~

Because what foo is constructing is a string that makes sense in the 
*caller*, not inside foo. What those statements do is concat the *value* 
of mode (i.e. "Y" or "X") and the *value* of value (i.e. "3" or "2") to 
the string.

It's equivalent to rust using the ${e} to do variable substitution.

> For example, why here I can simply write:
>
> void main() {
>      int b = 5;
>      mixin(`int a = b;`);
>      assert(a == 5);
> }

Because b makes sense in the context of main.

> Why should not I write like this:
>
> void main() {
>      int b = 5;
>      mixin(`"int a = " ` ~ b ~ ` ";"`);
>      assert(a == 5);
> }

Because it won't compile :) Mixin strings must be constructable at 
compile time, the value of b depends on runtime. Not to mention that you 
can't concat strings with ints.

-Steve


More information about the Digitalmars-d-learn mailing list