D doesn't have real closures
Russell Lewis
webmaster at villagersonline.com
Thu Sep 13 13:49:26 PDT 2007
BCS wrote:
> Reply to Russell,
>
>> 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:
>>
> [...]
>
> I like this idea.
>
> This would cover most cases where you want to have a persistent
> delegate. However it wouldn't cover the cases where the action is
> expected to modify function state. However most of the time you wont
> want to do that in a persistent delegate. What is more likely is that
> you will want to create two delegates with shared persistent state. But
> then you might as well generate a struct. Which, come to think of it,
> get back to the Idea I have always liked; delegate literals from
> arbitrary scope.
I thought about these issues, but decided to not include them in the
original post for simplicity. :)
I wanted to amplify and formalize a *VERY COOL* syntax that you used in
your example below, which I call "pseudo-member" syntax:
DEFINITION
The "pseudo-member" syntax is defined as:
<structOrClassVariable>.delegate <retVal>(<args>) { <body> }
to be syntax sugar for the following:
delegate <retVal>(<args>)
{
auto this = curry <structOrClassVariable>;
<modifiedBody>
}
where <modifiedBody> is the same as <body> except that, the expressions
within are modified to use "this.<member>" as appropriate.
EXAMPLE
struct Foo {
int a,b,c;
}
void delegate(int) BuildSettor(Foo *ptr)
{
return ptr.delegate void(int val) { a = b = c = val; }
// the line above is equivalent to:
return delegate void(int val)
{
auto this = curry val;
this.a = this.b = this.c = val;
}
}
NOTE: This syntax would *NOT* give access to private fields. Since it
is simply syntax sugar for a delegate literal, it is limited to the
access rights of the creator.
> void fn()
> {
> struct S
> {
> int i;
> int j;
> int at;
> };
>
> S* s = new S // darn I want anon structs
> alias s this; // might this work?
>
> i = 5;
> j = 10;
>
> Funky(s.{at = i;}, s.{at++; return at > j;} s.{return at;}); //make
> three delegates that uses 's' as context ptr.
> }
More information about the Digitalmars-d-announce
mailing list