Full closures for D

Daniel Keep daniel.keep.lists at gmail.com
Mon Nov 5 16:46:50 PST 2007



Jari-Matti Mäkelä wrote:
> BCS wrote:
> 
>> string mixins are fun:
>>
>> typeof(mixin(expr)) delegate() future(char[] expr)()
>> {
>>     typeof(mixin(expr)) res;
>>     auto t = new Thread({res = mixin(expr);});
>>     t.start;
>>     return { t.wait; return res; }
>> }
>>
>> auto hard_result = future!("hard_expression");
>> // Do stuff ...
>> use_result(hard_result());
>>
>>
>> NOTE: this runs into the issue that there is no way to get a template to
>> play with the local variables of a function. If there were a way to do
>> this I can think of a number of very cool things that could be done.
> 
> Yea, bummer :| I would have expected this to work: 
> 
> char[] bar(char[] foo) {
>   char[] tmp;
> 
>   tmp ~= "alias ";
>   foreach(p; foo)
>     if (p == ',') tmp ~= ", alias ";
>     else tmp ~= p;
> 
>   return tmp;
> }
> 
> template future(char[] aliases, char[] expr) {
> mixin(typeof(mixin(expr)).stringof ~ ` delegate() future(` ~ bar(aliases) ~
> `)()
> {
>   ` ~ typeof(mixin(expr)).stringof ~ ` res;
>   auto t = new Thread({res = mixin(expr);});
>   t.start;
>   return { t.wait; return res; };
> }`);
> }
> 
> void main() {
>   int a = 1, b = 2;
>   auto hard_result = future!("a,b", "a+b+39")!()();
> }
> 
> 
> Seems like Walter has at least two bugs to solve before that happens..

It's not a bug that future can't see a or b.  They're called "visibility
rules" and we have them for a reason, boy.  Without rules, there's just
*chaos* and chaos is... ugh, I don't even want to *think* about it.

You could cheat and do this, though:

void main() {
  int a = 1, b = 2;
  auto hard_result = mixin(future("a,b","a+b+39"));
}

Since the string mixin gets expanded into the context of the function.
But, as you can see, it's ugly and clumsy.  Just stick to lazy arguments
for Pete's sake :P

	-- Daniel



More information about the Digitalmars-d mailing list