Tuple mixins

Daniel Keep daniel.keep.lists at gmail.com
Fri May 11 01:43:06 PDT 2007


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.

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

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

-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

http://xkcd.com/

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/


More information about the Digitalmars-d-learn mailing list