Ranges and random numbers -- again

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Tue Jun 18 03:27:03 PDT 2013


On 06/18/2013 11:00 AM, monarch_dodra wrote:
> The last issue is input vs forward. IMO, PRNG's should be input by *default*,
> and forward (when possible) on demand.

I think that's potentially a very good design concept, and might offer a
friendly way round the issues I mentioned with rndGen.take() in my email of a
few minutes ago.

> Making a PRNG forward by default means you can't prevent an algorithm from saving
> your range. That means that *even* if you have a reference type, you could still
> have duplicate series.

Indeed -- I was about to follow up on my rndGen.take example with one involving
a final class version of MersenneTwisterEngine, but I think it's obvious without
the example :-)

> In the above example with dual call to "array", one can *hope* to have two different
> ranges... but there is nothing preventing array from calling "save" just to
> troll the user. fill does (used to) do it :D
> 
> I was also able to implement this pretty easily: Just give the saveable ranges
> the "dup" primitive. Users of the PRNG can then explicitly dup if they want to
> very safely and explicitly. If they really want a ForwardPRNG, then a simple
> adaptor that adds save in terms of dup is provided.

I think in principle one could have a .forward() method/property that would
return a forward-range wrapper of the range in question.

So, with this concept, one would expect,

    auto t1 = rndGen.take(5);
    writeln(t1);

    auto t2 = rndGen.take(5);
    writeln(t2);

... to produce _different_ sequences (as rndGen would be merely an input range,
and not .save-able), whereas

    auto gen = rndGen.forward;

    auto t1 = gen.take(5);
    writeln(t1);

    auto t2 = gen.take(5);
    writeln(t2);

.... would produce identical sequences as before.

It could in turn be a good design principle that pseudo-random sequences (and
random ranges deriving from pseudo-random sequences) should define the .forward
property, whereas "true" random sequences and their derivatives would lack it.


More information about the Digitalmars-d mailing list