On Monday, 20 November 2023 at 16:32:22 UTC, evilrat wrote:


```d
// this is a function returning a delegate
auto createCounter(int nextValue) => auto delegate() => nextValue++;


Thank you!!!.

Compiler forces me to omit "auto" keyword

```d
auto createCounter(int nextValue) => delegate () => nextValue++ ;
```

Explicit return must be specified after "delegate" keyword

```d
auto createCounter(int nextValue) => delegate int () => nextValue++ ;
```

When declaring a type (variable or parameter) is when keywords order must be "inverted"

```d
import std.stdio;
int callWith10( int delegate (int) x) =>x(10);
void main(){
  int j=100;
  // Explicit
  writeln( callWith10( delegate int (int i)=>i+j ) );
  // Inferred
  writeln( callWith10( i=>i+j ) );
  // OMG
  writeln( ( i=>i+j ).callWith10 );
}
```



// this is a function returning a function
auto createCounter(int nextValue) => auto function() => nextValue++;
```

I think this will not work, because nextValue is defined out of the returned function scope: you must return a closure (delegate).

Thanks a lot evilrat!!!

**From your answer (and other ones too) I have to say that...**

* **D Closures rocks!!!** It is hard to find something so powerful in other natively compiled languages: **Heap + GC** has it's advantages.

* **D offers nice syntax features**: you can declare arrow methods very similar to dart, or assign an arrow function/delegate to a variable like Javascript/Typescript lambdas.










Reply via email to