phobos icon indicating copy to clipboard operation
phobos copied to clipboard

std.range.choose should use `lazy` arguments

Open MrcSnm opened this issue 10 months ago • 3 comments

Given that example code:

auto getRangeA()
{
    import std.stdio;
    writeln("Range A");
    static struct RangeA
    {
        void popFront(){}
        bool front(){return true;}
        bool empty(){return true;}
    }
    return RangeA();
}
auto getRangeB()
{
    import std.stdio;
    writeln("Range B");
    static struct RangeB
    {
        void popFront(){}
        bool front(){return true;}
        bool empty(){return true;}
    }
    return RangeB();
}


void main() 
{
    import std.range;
    choose(true, getRangeA, getRangeB);
}

You can see that both ranges needs to be constructed, even though it is guaranteed only one of them will be used. And they don't even escape the scope. The problem is that one may need to build the range to use it and that may take a plenty of time.

MrcSnm avatar Mar 01 '25 01:03 MrcSnm

Hello @MrcSnm I would like to work on this issue. can you please assign to me.

Gauravsh-24 avatar Mar 01 '25 06:03 Gauravsh-24

Thos sounds like a phobos bug, not a dmd bug. Is it?

thewilsonator avatar Mar 01 '25 09:03 thewilsonator

Unfortunately I don't think this kind of behavioral change to a public interface is allowed given Phobos' backward-compatibility policy. There may be existing code that relies on these side effects happening.

As a workaround, it should be possible to create a wrapper that forces a range to be evaluated lazily (by accepting it as a lazy argument). We could then write:

auto lazyRange(R)(lazy R r)
{
    // left as an exercise
}

void main()
{
    choose(true, lazyRange(getRangeA), lazyRange(getRangeB));
}

...and this would have the desired behavior, without any risk of breaking compatibility.

pbackus avatar Mar 11 '25 03:03 pbackus