Delegates

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Wed Jan 24 15:58:21 PST 2007


Robin Allen wrote:
> Frits van Bommel Wrote:
> 
>> Robin Allen wrote:
>>> I'm trying to figure out delegates. From what I can see, they're intended to be what other languages call closures?
>>>
>>> So, say I wanted to write some functions for signal processing. I'd define a Wave type as a function of time, like this:
>>>
>>> alias float delegate(float) Wave;
>>>
>>> and a function to return a sine wave of a specified frequency like this:
>>>
>>> Wave sine(float freq)
>>> {
>>>   return delegate(float t) { return std.math.sin(2*std.math.PI*t); };
>>> }
>> [Snipped some similar examples]
>>
>> Returning delegate literals is never a good idea.
>> A recent thread "Trouble with anon delegates." should explain the issue. 
>> I suggest you read it :).
> 
> Thanks, that cleared things up a bit. From what was said in that thread, it looks like what I'm trying to do isn't possible. Making it so that you *can* return delegate literals would be a good move IMO, but I've no idea how plausible that is (though I do know Lua and ECMAscript let you do it).

Yes, scripting languages often allow it, as do functional languages.

It's something that comes up rather often though, and someday Walter may 
be persuaded to implement it. It may be a bit tricky to do 
(efficiently), though.

There's a workaround, by the way:
-----
// Warning: untested code, but something like this should work.
float delegate(float) foo(float freq)
{
     struct Data
     {
         float freq;
         float foo(float t) { return freq * t; } // or whatever
     }
     Data* d = new Data;
     d.freq = freq;
     return &d.foo;
}
-----

It's certainly not as pretty, but it gets the job done.


More information about the Digitalmars-d-learn mailing list