seeding the pot for 2.0 features

Kristian Kilpi kjkilpi at gmail.com
Sat Jan 27 00:55:11 PST 2007


On Thu, 25 Jan 2007 20:08:29 +0200, BCS <BCS at pathlink.com> wrote:
> Kristian Kilpi wrote:
>> On Wed, 24 Jan 2007 02:09:09 +0200, BCS <ao at pathlink.com> wrote:
>> [snip]
>>
>>> my choice: dynamic init structs and explicit context for delegates
>>>
>>> int i,j,k;
>>> // pickle i,j,k then use them
>>> auto (new struct {int i_ = i; int j_ = j; int k_ = k; }).delegate(int   
>>> m){return ((i_ * m)+j_)*m +k_;}
>>>
>>  While we are at it, why not just let the compiler to generate context  
>> for  delegates? ;)
>> E.g.
>>    int i, j;
>>   return int delegete(int m) {return i * m + j;}
>> ->
>>   return int (new struct {int i_ = i; int j_ = j}).delegete(int m)  
>> {return  i_ * m + j_;}
>
>
> I think that has been proposed but has some problems. For instance
>
>
> auto dg = int delegate(int m) {return i * m + j;}
>
> fnUsingDg(dg);	// doesn't need context
>
> i++;
> j++;	// did that effect the context?
>
> if(boolFn())
> 	return dg;	// now we need context
> else
> 			// or do we??
> 	return int delegate(int m) {return i + j;}
[snip]

Hmm, yep, that's problematic.
First, I tried to come up with some simple rules, For example, the context  
should be automatically generated when:

   1) A delegate is returned.

   2) A delegate is assigned to something that is not a local variable.
      A class object is considered to be a local when 'scope' is used with  
it.

But, nothing is ever so simple, isn't it? ;) They (the rules) would likely  
cause *way* more trouble than good.

However, it would be nice if one could tell the compiler to automatically  
create the context for a delegate (probably your explicit syntax should be  
possible too). For example, *something* like this:

   dg.createContext();  //compiler generates the context


Hmm, maybe the compiler should automatically generate context for  
anonymous delegates, after all, when they are returned from a function:

   int i, j;
   return delegate int(int m) {return i + j;};  //creates context

But not when it's returned via a variable:

   int i, j;
   auto dg = delegate int(int m) {return i + j;};
   return dg;  //no context is created

You would have to call 'createContext()' by yourself.

Preventing context from being generated should also be possible, of course:

   return (delegate int(int m) {return i + j;}).noContext();  //don't  
create context


I think implicit context for anonymous delegates returned from functions  
would reduce the number of errors people will make with them. But it's an  
exception to the rules, which is never good.



More information about the Digitalmars-d mailing list