November 21, 2023

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

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

Thank you!!!.

Compiler forces me to omit "auto" keyword

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

Explicit return must be specified after "delegate" keyword

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

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

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.

November 21, 2023

On Monday, 20 November 2023 at 16:47:13 UTC, Paul Backus wrote:

>

You can put the delegate keyword in front of the function literal:

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

This syntax is documented in the spec's section on Function Literals (look at the grammar box and the examples).

Thaks Paul

1 2
Next ›   Last »