Expression-bodied functions

ZombineDev via Digitalmars-d digitalmars-d at puremagic.com
Sat Jan 2 15:54:21 PST 2016


On Saturday, 2 January 2016 at 15:04:15 UTC, Enamex wrote:
> On Friday, 1 January 2016 at 00:27:49 UTC, ZombineDev wrote:
>> By the way, a very similar language feature was approved and 
>> implemented for the upcomming DMD 2.070 release. It allows you 
>> to use a short syntax for function templates:
>>
>> alias add = (a, b) => a + b;
>> // Shorthand for:
>> // auto add(T1, T2)(T1 a, T2 b) { return a + b; }
>>
>> IFTI makes it look like a regular function call:
>> writeln(add(3, 4.5));
>>
>> It works for free functions, but I'm not sure if it would also 
>> work for member-functions (methods).
>>
>> https://issues.dlang.org/show_bug.cgi?id=12421
>
> IMHO, anything like that is just a tangential 'fix' to the fact 
> that D's design rests on commands like 'return' to leave scope 
> and return values.
>
> Something like
>
> auto add(auto x, auto y) { x + y }
>
> would be much more wholesome IMO. (The 'funcName(auto arg)' 
> syntax is just a convenience suggestions; the important part is 
> '{ x + y }').

Personally, I prefer the new alias syntax, (which sort of reminds 
me of Haskell), because it looks much cleaner than this mashup of 
Swift and C++14.

> That said, it does fix something that 'alias' should've been 
> able to do from the beginning. I'm not sure what else but I 
> think there other places where alias needs '= I!(stuff)' 
> identity template to accept the 'stuff'.

The most obvious thing that comes to my mind are values (that 
enum accepts):
enum number = 3;
alias aliasedNumber = I!(3);

However wouldn't this blur the line between enum and alias too 
much?
Right now enum can refer only to values computed at compile-time, 
while alias can only refer to symbols*, which I think is a good 
separation.

* Alias to a function literal refers to the _symbol_ of the 
anonymous function template.

Maybe a good direction forward would be to allow alias to refer 
to expressions (i.e. similar to the AST macros idea), which you 
can introspect at CT (like with CT type reflection).

auto query = db.orders
     .where!@{price > 200}
     .select!(order => order.name);

@{...} looks like q{...} but would capture the AST of the 
expession between the braces (which must be valid D code).

auto where(alias predExpr, R)(R range)
     if (isInputRange!R &&
         isAstCapture!predExpr)
{
     // http://dlang.org/spec/expression.html#OrOrExpression
     static assert(__traits(isExpression, OrOrExpression, 
predExpr);

     // prepare where clause of SQL statement...
}




More information about the Digitalmars-d mailing list