Patterns to avoid GC with capturing closures?

Steven Schveighoffer schveiguy at gmail.com
Fri Aug 24 15:23:10 UTC 2018


On 8/24/18 11:18 AM, Peter Alexander wrote:
> Consider this code, which is used as an example only:
> 
> auto scaleAll(int[] xs, int m) {
>    return xs.map!(x => m * x);
> }
> 
> As m is captured, the delegate for map will rightly allocate the closure 
> in the GC heap.
> 
> In C++, you would write the lambda to capture m by value, but this is 
> not a facility in D.
> 
> I can write scaleAll like this:
> 
> auto scaleAll(int[] xs, int m) @nogc {
>    return repeat(m).zip(xs).map!(mx => mx[0] * mx[1]);
> }
> 
> So that repeat(m) stores m, but it is quite hacky to work like this.
> 
> I could write my own range that does this, but this is also not desirable.
> 
> Are there any established patterns, libraries, or language features that 
> can help avoid the GC allocation in a principled way here?

This is somewhat related to a suggestion I had last month: 
https://forum.dlang.org/post/pjnue1$olt$1@digitalmars.com

I also hate to have such a thing allocate. The only scalable solution I 
can think of is to write your own range function which has the 
appropriate state saved by value. But then you lose all the goodies from 
Phobos.

Having a way to capture state and give that state to std.algorithm 
ranges would be really cool.

-Steve


More information about the Digitalmars-d-learn mailing list