Anonymous function syntax
Christophe
travert at phare.normalesup.org
Fri Sep 23 01:35:36 PDT 2011
Andrei Alexandrescu , dans le message (digitalmars.D:145023), a écrit :
>> What is the problem with just inferring the `return`, allowing you to replace
>> (a,b) { return a + b; }
>>
>> with
>> (a, b) { a + b; }
> The objection is that it introduces a number of questions:
>
> 1. How about using that syntax in regular functions?
> 2. What if the lambda wants to actually evaluate the expression but
> return void?
> 3. How is the semicolon relevant? (If its presence is used as a
> disambiguator for (2), it's poor design to predicate a large semantic
> difference on such a distinction.)
I think such shortcut should be allowed only for one-liners. There is no
gain not to write return if you already have several statements.
The shortcut syntax should be
(a, b) { expression },
and not
(a, b) { statement }
This way, you ensure that only one liners can use this syntax, so there
is no abuse.
It is true that the return type would depend on the presence of a
semicolon, but the compiler will quickly complain if it expects a
delegate returning void and gets a delegate returning a type, or
vice-versa anyway.
>> Also would it make sense to have a template library along the lines of boost::proto/boost::lambda to allow even
>> shorter, expression-based lambdas like
>>
>> _1 + _2
>>
>> I'm not exactly a D template metaprogramming pro, but I think this would work for a lot of common cases.
>
> Such an approach has caused more trouble than benefits in C++.
Too dangerous. std.algorithm uses a, b, c, etc, but it can only do that
because it never checks the context:
int b;
double x;
auto f = lambda { a * x + b }
How many arguments does f take ?
--
Christophe
More information about the Digitalmars-d
mailing list