-
-
Notifications
You must be signed in to change notification settings - Fork 706
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
Fix Issue 18631 - std.random.choice does not work with const arrays #8495
Conversation
|
Thanks for your pull request and interest in making D better, @GrimMaple! We are looking forward to reviewing it, and you should be hearing from a maintainer soon.
Please see CONTRIBUTING.md for more information. If you have addressed all reviews or aren't sure how to proceed, don't hesitate to ping us with a simple comment. Bugzilla references
Testing this PR locallyIf you don't have a local development environment setup, you can use Digger to test this PR: dub run digger -- build "master + phobos#8495" |
|
The documentation says: With this change, ranges that have a |
Please, provide a concrete example |
struct Range
{
int x;
ref int front() return {return x;}
ref int back() return {return x;}
void popFront() {}
void popBack() {}
bool empty = false;
Range save() {return this;}
size_t length = 10;
alias opDollar = length;
ref int opIndex(size_t i) return {return x;}
}
void main()
{
import std.random, std.range;
auto r = Range(10);
int* x = &choice(r);
}After this PR: |
|
This can be fixed if I add overloads that accept (EDIT: and return) /// ditto
ref auto choice(Range, RandomGen = Random)(ref Range range, ref RandomGen urng)
{
assert(range.length > 0,
__PRETTY_FUNCTION__ ~ ": invalid Range supplied. Range cannot be empty");
return range[uniform(size_t(0), $, urng)];
}
/// ditto
ref auto choice(Range)(ref Range range)
{
return choice(range, rndGen);
}Is that acceptable? |
Not sure. I'd wager most ranges have references to their elements, so it's a rare case to support. One range with elements inside it is |
The documentation already says |
|
Please note that provided solution for suspect range misses |
In my example, |
|
Since I started this with a post in discord, I'll chime in.
ref choice(Range)(ref Range range)
if (!isInputRange!Range && __traits(isDynamicArray, Range))
{
return choice(range[]);
}
ref choice(Range, RandomGen)(ref Range range, ref RandomGen urng)
if (!isInputRange!Range && __traits(isDynamicArray, Range))
{
return choice(range[], urng);
}This pattern is ugly, but I don't see another way to do it without breaking the example, or without splitting the |
|
I have updated the code to support the scenario provided by dkorpel. Provided scenario is also added as a unittest |
`auto ref` is not needed on `Range` param
auto refis not needed onRangeparamAn overload with explicit
ref Rangeadded to support ranges returningref