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

Rank does not iterate source on re-iterations #1065

Closed
atifaziz opened this issue Apr 27, 2024 · 0 comments · Fixed by #1064
Closed

Rank does not iterate source on re-iterations #1065

atifaziz opened this issue Apr 27, 2024 · 0 comments · Fixed by #1064
Labels
Milestone

Comments

@atifaziz
Copy link
Member

The following code demonstrates this bug:

var xs = Enumerable.Range(1, 5)
                   .Select(x => x * 10)
                   .ToArray();

IEnumerable<int> Unstable()
{
    try
    {	        
        foreach (var x in xs)
            yield return x;
    }
    finally
    {
        // rotate array elements by 1
        var x0 = xs[0];
        Array.Copy(xs, 1, xs, 0, xs.Length - 1);
        xs[^1] = x0;
    }
}

var result = Unstable().Rank();
foreach (var _ in xs)
    Console.WriteLine(result.ToDelimitedString(", "));

The output should have been:

5, 4, 3, 2, 1
4, 3, 2, 1, 5
3, 2, 1, 5, 4
2, 1, 5, 4, 3
1, 5, 4, 3, 2

Instead, it is:

5, 4, 3, 2, 1
5, 4, 3, 2, 1
5, 4, 3, 2, 1
5, 4, 3, 2, 1
5, 4, 3, 2, 1

It seems that Rank caches the source on the first iteration and reuses it on subsequent re-iterations. The culprit appears to be the following line:

source = source.ToArray(); // avoid enumerating source twice

which modifies the original captured source.

This bug is present in the latest release (4.2).

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

Successfully merging a pull request may close this issue.

1 participant