passing a variadic parameter to randomSample
H. S. Teoh
hsteoh at quickfur.ath.cx
Tue Jan 25 22:35:59 UTC 2022
On Tue, Jan 25, 2022 at 02:07:43PM -0800, Ali Çehreli via Digitalmars-d-learn wrote:
[...]
> auto RandomChoice(R)(R[] r...)
>
> > {
> > auto rnd = MinstdRand0(unpredictableSeed);
> > return only(r).randomSample(1, rnd).front;
>
> Which makes that simpler as well because being a slice, r is already a
> range. And there is choice():
>
> return r.choice(rnd);
>
> Something is very important though: The 'r' slice is short-lived; it does
> not live in dynamic memory. RandomChoice() should not save it for later use
> nor return it. (The compiler may have protection against that; I am not
> sure.)
I think with -dip1000 the compiler should refuse to compile the code if
you try to save a slice of r past the function body.
T
--
Philosophy: how to make a career out of daydreaming.
More information about the Digitalmars-d-learn
mailing list