Full closures for D

Bill Baxter dnewsgroup at billbaxter.com
Wed Nov 7 12:27:08 PST 2007


Simas wrote:
> Nathan Reed Wrote:
> 
>> David B. Held wrote:
>>> In order to analyze this properly, we need to look at my (working) 
>>> definition of map():
>>>
>>> T[] map(T)(T delegate(T) f, T[] list)
>>> {
>>>    T[] result;
>>>    foreach (e; list) result ~= f(e);
>>>    return result;
>>> }
>>>
>>> Ok, what I propose is that
>>>
>>>    typeof({ return base ~ $0; }) == T delegate(T)
>>>
>>> which is easy enough to infer, because that is the declared type of f, 
>>> to which the delegate is bound!  No brain surgery there.  How do we know 
>>> what T is?  Well, that's easy enough to infer from list.  And you're 
>>> done.  The mechanics of it isn't that hard.  The question is whether the 
>>> idea of implicit arguments makes people's stomachs turn or not.
>>>
>>> Dave
>> Of course, in this case it's "easy enough to infer".  However, function 
>> bodies can be arbitrarily complicated, meaning you will need a full type 
>> inference engine for this to work in the general case.
> 
> Not really. The compiler knows what the return-type is.
> 
>> That adds so much complexity to the compiler that it's simply not worth 
>> it for the slight extra convenience.  Besides, it's just fundamentally 
>> not in the philosophy of D to do things like this.  As other people have 
>> pointed out, if you want to program like you would in Perl, you should 
>> use...Perl.
> 
> On "http://www.digitalmars.com/d/" D is defined as "Its focus is on combining the power and high performance of C and C++ with the programmer productivity of modern languages like Ruby and Python."
> 
> Well, somebody may say perl isn't modern. But in Ruby and Python this is also possible. So, why is this wrong? Only why this is not C-style? 

In python the lambdas still requires arguments to be named, and use of 
the 'lambda' keyword.  So it'd be something like:
     absDirs = map(lambda x: base + x, readdir(DIR))

I'd prefer that middle ground to perl's magic variables.  Make it so the 
type can be inferred, but the user still has to give it a name.  Maybe:

    auto base = "/path/to/dir/";
    auto absoluteDirs = map((x){ return base ~ x; }, readdir(DIR));

But I find the the Python (or Perl) much easier to look at without all 
the (){}; business around the anonymous function.

--bb



More information about the Digitalmars-d mailing list