Can we fix this?

Imperatorn johan_forsberg_86 at hotmail.com
Wed Sep 29 21:30:00 UTC 2021


On Wednesday, 29 September 2021 at 16:47:23 UTC, Steven 
Schveighoffer wrote:
> On 9/29/21 10:16 AM, jfondren wrote:
>> [...]
>
> This is not what I would have ever thought of, and it's kind of 
> prone to error, since `i` is still used from within the lambda. 
> It would not be hard to mess it up:
>
> ```d
> foreach(int i; [1, 2, 3]) (){
>     dgList ~= { writeln(i + 2); }; // still outputs 5 5 5
> }();
> ```
>
> What we need is a syntax to specify which values are captured 
> and which variables are referenced.
>
> What I normally do if I need something like this is:
>
> ```d
> foreach(int i; [1, 2, 3]) {
>    dgList ~= (b) { return {writeln(b);};} (i + 2);
>    // or less error prone:
>    dgList ~= (i) { return {writeln(i + 2);};} (i);
> }
>
> ```
>
> Which specifies the captured variable. But it's a lot of 
> punctuation.
>
> Some imagined syntax?
>
> ```d
> dgList ~= (@capture i) {writeln(i + 2);};
> // or:
> dgList ~= (@capture i) => writeln(i + 2);
> ```
>
> -Steve

Tbh I'd be for any change that could improve something.

But why can't we just do something minimal, like use what we have 
(commenting on imagined syntax)

(i) { /*use i here*/ } or
(i) => { /*use i here*/ }

Could we solve it without introducing attributes or reusing some?

Personally I'm used to the lambda expression so I wouldn't mind 
using that. But can we just do something more sane than what we 
currently have?

If I ask kindly?


More information about the Digitalmars-d mailing list