Breaking ";" rule with lambda functions

Andrey Zherikov andrey.zherikov at gmail.com
Tue Aug 2 11:27:05 UTC 2022


On Monday, 1 August 2022 at 14:15:31 UTC, pascal111 wrote:
> We all know the strange syntax of lambda function within filter 
> algorithm like "auto r = chain(a, b).filter!(a => a > 0);".

TBH I don't find lambda syntax strange - it's pretty nice and 
there are two forms (unlike in C++): short one (`a => a > 0`) and 
long one (`(a) { return a > 0; }`).

Compare to C++ lambda syntax: `[](auto a) { return a > 0; }`

> My note is, don't we break D rules by leaving ";" after lambda 
> function syntax?!

There is no breakage: `a => a > 0` in this example is a 
(template) parameter to `filter` function. You can rewrite it in 
different ways, like: `filter!((a) { return a > 0; })` or

```d
alias criteria = (a) { return a > 0; };
auto r = chain(a, b).filter!criteria;
```

or even longer:

```d
auto criteria(T)(T a)
{
     return a > 0;
}

auto r = chain(a, b).filter!criteria;
```

> Many of D rules are taken from C, we know that, so a general 
> basic rule is to put ";" after each statement

I think this is more or less correct but I personally like that I 
don't need to put ";" after definition of a class or struct 
unlike in C.

> so the previous statement of filter should be "auto r = 
> chain(a, b).filter!(a => a > 0;);"? Why D leaves ";" in this 
> case?

No. it should not. The statement here is `auto r = chain(a, 
b).filter!(a => a > 0);`, not `a => a > 0`. If you use longer 
version of lambda syntax then yes, you'll see ";" there: `auto r 
= chain(a, b).filter!((a) { return a > 0; });` but ";" is not 
after lambda function, it's inside because you have `{...}` 
function body (which, I believe, is defined as a sequence of 
statements so you have ";" there).

Again, both `a => a > 0` and `(a) { return a > 0; }` are just 
parameters to `filter` function. Parameters are not terminated 
with ";". This is the same as in C - you are not adding ";" after 
function parameter:
```cpp
auto is_even = [](int i){ return i%2 == 0; };
auto result = std::find(..., ..., is_even);
```


More information about the Digitalmars-d-learn mailing list