Mir Random [WIP]

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Thu Nov 24 05:45:40 PST 2016


On Thursday, November 24, 2016 09:05:34 Kagamin via Digitalmars-d wrote:
> On Wednesday, 23 November 2016 at 21:33:53 UTC, Jonathan M Davis
>
> wrote:
> > though I think that using the comma operator like that is
> > deprecated now. Adding a helper function such as
> >
> > auto getNext(R)(ref R range)
> >     if(isInputRange!R)
> > {
> >     range.popFront();
> >     return range.front;
> > }
> >
> > would solve that problem.
>
> It's the same behavior and suffers from the same problem of reuse
> of RNG output.

How so? Because someone might call range.front again without bothering to
call popFront? If you're paranoid about that, then it can call popFront
again before returning (though that would be wasteful).

My take on it is that if you just call popFront before using the random
number generator range, then you don't have to worry about what any other
code that used it did.

Regardless, the range API is _way_ more useful in general than something
like rand(). And if anyone is trying to avoid ranges with random numbers, I
think that they're just making their life harder. Occasionally, it's useful
to get just one random number, in which case, having to deal with the range
API over rand() is kind of annoying, but in general, it's not a problem, and
the wrapper function that I suggested basically gives you rand() from a
range of random numbers.

Alternatively, you could just do rndGen().take(1).front, and as long as
rndGen() gives you a reference type, it works just fine. Unfortunately,
std.random did not use reference types for its ranges. _That_ is the big
mistake of std.random and the main item that needs to be fixed. There are
some other subtleties (e.g. it's useful to be able to save the state of a
random number generating range, but you don't necessarily really want it to
be a forward range), but those are minor in comparison to the mistake of
std.random using value types rather than reference types for ranges.

- Jonathan M Davis



More information about the Digitalmars-d mailing list