Mir Random and Dlang Ranges [Example]

Ilya Yaroshenko via Digitalmars-d digitalmars-d at puremagic.com
Fri Nov 25 07:56:45 PST 2016


On Friday, 25 November 2016 at 15:09:46 UTC, Joseph Rushton 
Wakeling wrote:
> * its own internal state (or at least, those parts of it that 
> correspond to state underlying the pseudo-random process, which 
> is NOT limited to the RNG state) is not at risk of being copied 
> by value;

What kind of state should not be copied by value? I thought it is 
only an Engine.
Engines can not be copied by value in Mir Random. If you mean 
counters, than it is not correct for Dlang. Almost all D counters 
like ranges are copied by value. A `ref` for randomSample should 
be used to functions if thay want to modify its counters (the 
same logic exists in std.experimental.primitives like popFront ).

> * it's possible to generate multiple `RandomSample` instances 
> deep in the inner loop of a program, without creating slow-down 
> related to memory allocation (this was the reason I abandoned a 
> class-based approach);

No problem, the same approach like for RandomRange should work.

> * it's easy to fit the `RandomSample` implementation into a 
> range chain.

No problem, ditto

> The last point doesn't have to be quite as simple as the sort 
> of thing you can do currently, such as:
>
>     iota(100).randomSample(10, rng).filter!(a => a > 
> 50).writeln;

Why not? rng can be passed by ref and and its pointer can be 
preserved internally. So the same syntax will work in Mir Random.

> Ideally it would be possible to create a function that creates 
> that kind of range chain and returns it, as in:
>
>     auto myMagicRange(RNG)(size_t n, size_t m, ref RNG rng)
>     {
>         assert(n < m);
>
>         return iota(m).randomSample(n, rng).filter!(a => a > 
> n/2);
>     }
>
>     // Now output 10,000 unique filtered samples ...
>     foreach (_; 0 .. 10_000)
>     {
>         myMagicRange(10, 100, rng).writeln;
>     }

This works for RandomRange and can be done for RandomSample the 
same way.

BTW, I am looking for your RandomSample PR! :-)

range.algorithm [1] seems to be a proper module for it (it is 
small for now, so your name should be the first here).

[1] 
https://github.com/libmir/mir-random/blob/master/source/random/algorithm.d


More information about the Digitalmars-d mailing list