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:
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") );
}