proposal: @mixin functions to auto-mixin at call site

Timothee Cour thelastmammoth at gmail.com
Mon Sep 2 21:15:05 PDT 2013


I'd like to be able to declare a function with a special @mixin property
that will auto-mixin at call site:

@mixin string foo(){return some_string;}
void main(){
 foo; //behaves as mixin(foo()); if @mixin weren't provided
}

This is purely syntax sugar, as it could be done with a mixin at call site,
but is very useful in a number of scenarios:

Example 1:
I wrote a string parsing function 'embed' that allows to embed variables in
current scope in a string:
void main(){
int x1=11;
double x2=2.3;
assert(mixin("variables: x1=$x1, x2=$x2, sum=$(x1+x2)".embed) ==
"variables: x1=11, x2=2.3, sum=13.3");
}
The 'embed' function parses the input string, extracts the '$' tokens (with
a proper escape mechanism) and return a string of the form 'std.conv.text(
...)' with appropriate arguments so that the string can be mixed in at call
site as above.

Without the @mixin property we have:
mixin("variables: x1=$x1, x2=$x2, sum=$(x1+x2)".embed)

With the proposed @mixin property this would simplify to:
"variables: x1=$x1, x2=$x2, sum=$(x1+x2)".embed

Which is simpler and easier to read than:

text("variables: x1=",x1,", x2=",x2,", sum=",x1+x2);


There are many other use cases.

If for some reason we can't have @mixin special property, can we at least
have UFCS for mixin, so that we could write:
"variables: x1=$x1, x2=$x2, sum=$(x1+x2)".embed.mixin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20130902/2b39cabf/attachment.html>


More information about the Digitalmars-d mailing list