Tuple mixins

Max Samukha samukha at voliacable.com.removethis
Fri May 11 03:21:49 PDT 2007


On Fri, 11 May 2007 18:43:06 +1000, Daniel Keep
<daniel.keep.lists at gmail.com> wrote:

>
>Max Samukha wrote:
>> The mixin form compiles and works in some cases (in others it fails).
>> Is it legal at all? Is it mentioned anywhere in the specs? 
>> 
>> The following declares an int array and initializes it to the last
>> element encoded in the mixin string ([3]). Should the mixin fail with
>> an appropriate error or initialize the array to [1, 2, 3]?
>> 
>> void main()
>> { 
>>   int[] arrr = [mixin("1, 2, 3")];
>>   writefln(arrr);
>> }
>
>The problem here is that mixins are not direct string mixins.  That is,
>they don't simply spit their argument into the AST like a C preprocessor
>macro would.
>
>There are two kinds of string mixins: statement and expression.  The one
>above is an expression mixin.  Let's look at it a different way:
>
>int[] arr = [( mixin("1,2,3") )];
>
>If you look at it like that, you see that "1,2,3" is not a tuple at all;
>it's a comma-delimited list of expressions which itself evaluates to the
>*last* expression.

Thanks, Daniel. I know about the expression and statement mixins. What
I wanted to ask is why my example compiles? Is it a compiler bug or
another type of mixin partially (or incorrectly) implemented?

Note, that the mixin compiles in other similar contexts:

void foo(int a/*, int b, int c */) 
{
	writefln(a); // outputs 3
}

void main()
{
  foo(mixin("1, 2, 3"));
}

 

>
>If you wanted to actually mix in a tuple, you'd have to be a bit more
>creative:
>
>int[] arr = [mixin("Tuple!(1,2,3)")]; // Note: not tested

Then I'd do it like this:
int[] arr = mixin("[1,2,3]"); //ok, [1,2,3] is a complete expression

>
>I ran across this when I was trying to generate functions with a
>particular name.  Turns out this *doesn't* work:
>
>> void mixin(identName)()
>> {
>>     // Do stuff
>> }
>
>Basically, simple rule of thumb is: when mixing in an expression,
>mentally put a pair of parentheses around it; it helps you work out
>exactly what it's going to do.
>
>	-- Daniel


More information about the Digitalmars-d-learn mailing list