passing a variadic parameter to randomSample

vit vit at vit.vit
Tue Jan 25 11:50:08 UTC 2022


On Tuesday, 25 January 2022 at 09:48:25 UTC, forkit wrote:
> so I'm trying to write (or rather learn how to write) a 
> 'variadic template function', that returns just one of its 
> variadic parameter, randomly chosen.
>
> But can't get my head around the problem here :-(
>
> .. Error: template `std.random.randomSample` cannot deduce 
> function from argument types `
>
> // --
>
> module test;
> import std;
>
> string RandomChoice(R...)(R r)
> {
>     auto rnd = MinstdRand0(42);
>     return r.randomSample(1, rnd).to!string;
> }
>
> void main()
> {
>     writeln( RandomChoice("typeA", "typeB", "typeC") );
> }
>
> // --

`r` is not input range, try this:

```d
module test;
import std;


string RandomChoice1(R...)(R r)
{
     auto rnd = MinstdRand0(unpredictableSeed);
     return only(r).randomSample(1, rnd).front;
}

string RandomChoice2(R...)(R r)@nogc
{
	auto rnd = MinstdRand0(unpredictableSeed);

     switch(rnd.front % R.length){
         static foreach(enum I, alias arg; r){
         	case I:
             	return arg;
         }

         default:
         	assert(0, "no impl");
     }
}

void main()
{
     writeln( RandomChoice1("typeA", "typeB", "typeC") );
     writeln( RandomChoice2("typeA", "typeB", "typeC") );
}
```



More information about the Digitalmars-d-learn mailing list