Full closures for D

Jari-Matti Mäkelä jmjmak at utu.fi.invalid
Tue Nov 6 01:43:46 PST 2007


Daniel Keep wrote:

> 
> 
> 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 probably didn't notice but I used alias parameters there. So it should
be very much possible to refer to the variables after that. Made a small
bug though, should have been 

>>   auto hard_result = future!("a,b", "a+b+39")!(a,b)();

or perhaps

  char[] Future(char[] a, char[] b) {
    return `future!("` ~ a ~ `","` ~ b ~ `")!(` ~ a ~ `)`;
  }

  auto hard_result = mixin(Future("a,b", "a+b+39"))();

> 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.

Alias parameters work much better.



More information about the Digitalmars-d mailing list