D doesn't have real closures

Russell Lewis webmaster at villagersonline.com
Thu Sep 13 13:11:31 PDT 2007


Julio César Carrascal Urquijo wrote:
> Brad Anderson wrote:
>> http://www.hans-eric.com/2007/09/11/d-doesnt-have-real-closures/
> 
> I've posted a response on my blog:
> 
> http://jcesar.totumo.net/2007/09/13/d-should-have-real-closures/

I think that closures could be easily implemented using compiler-driven 
currying.  I'm thinking that we should add the syntax
	curry <exp>
which would be valid inside delegate and function literals, and which is 
defined to mean:

"The value of <exp> is evaluated at delegate literal creation time, and 
stored on the heap, then passed to the delegate literal at call time as 
a curried argument."

Basically, the compiler would take all of the curry expressions in a 
literal, build a struct on the heap which contained them, then pass a 
pointer to that struct as a curried argument to the delegate.

The thing I like about this is that it makes it obvious which arguments 
are passed on the heap (curry expressions) and which access stack 
variables (ordinary, non-curry expressions).  And it's compact enough 
that I think it could see practical use.



EXAMPLES

Let's start with a simple example.  You have an integer that you want to 
return to anybody who calls your delegate:
   int delegate() Foo()
   {
     int i = <whatever>;
     return delegate int() { return curry i; }
   }


Now, something more complex, where you use a curry expression in the 
left-hand side of an assignment (and note that you can use curry 
expressions on function arguments):
   void delegate(int) BuildAssigner(int *ptr)
   {
     return delegate void(int newVal) { *(curry ptr) = newVal; };
   }


Something which copies values from one to another (such as binding two 
things together in your GUI):
   void delegate() BuildDelayedCopier(int *dest,int *src)
   {
     return delegate void() { *(curry dest) = *(curry src); };
   }



Thoughts, anyone?



More information about the Digitalmars-d-announce mailing list