Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std.range.choose should use lazy arguments #10653

Open
MrcSnm opened this issue Mar 1, 2025 · 3 comments
Open

std.range.choose should use lazy arguments #10653

MrcSnm opened this issue Mar 1, 2025 · 3 comments

Comments

@MrcSnm
Copy link
Contributor

MrcSnm commented Mar 1, 2025

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.

@Gauravsh-24
Copy link

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

@thewilsonator
Copy link
Contributor

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

@dkorpel dkorpel transferred this issue from dlang/dmd Mar 1, 2025
@pbackus
Copy link
Contributor

pbackus commented Mar 11, 2025

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants