I think I have just found a pattern to ease the pain of @nogc programming somewhat. Consider this:

import std.algorithm;
import std.range;

@nogc void main()
{   import core.stdc.stdio;
    int power = 2;
    foreach
    (   raised;
        iota(10)
        .dropOne
        .map!(num => num^^power)
    ) printf("%d\n", raised);
}

It won't compile, because the lambda argument on map uses the local variable power. Compiler thinks it must allocate that variable in heap, using gc, lest the lambda function could overlive power.

So that is probably one big reason for complains about Phobos when you can't use the garbage collector. This hurdle won't make it useless, though. You can avoid the problem this way:

import std.algorithm;
import std.range;

@nogc void main()
{   import core.stdc.stdio;
    int power = 2;
    foreach
    (   raised;
        iota(10)
        .dropOne
        .zip(power.repeat)
        .map!(arg => arg[0]^^arg[1])
    ) printf("%d\n", raised);
}

It works, but arg[0] and arg[1] are fairly much book examples on how to NOT name your variables.

But with a little bit of help, the library can still do better:

import std.algorithm;
import std.range;

@nogc void main()
{   import core.stdc.stdio;
    int power = 2;
    foreach
    (   raised;
        iota(10)
        .dropOne
        .zip(power.repeat)
        .map!(tupArg!((num, pow) => num^^pow))
    ) printf("%d\n", raised);
}

alias tupArg(alias func) = x => func(x.expand);


Yes, it makes the syntax heavier, and in a simple case like this it's arguable whether it's worth it.

But for me at least, when the complexity of the map alias parameter starts rising, having the ability to name your variables definitely pays back.

What are your thoughts? Do you agree with this coding pattern?

Reply via email to