Alternative to std.range.choose
James Gray
test at test.com
Wed Jul 22 04:33:20 UTC 2020
Is there a better way to achieve behaviour similar to rangeFuncIf
below? f gives a contrived example of when one might want this. g
is
how one might try and achieve the same with std.range.choose.
import std.stdio;
import std.range : only, chain, join, choose;
import std.algorithm : map;
auto rangeFunctIf(alias F1, alias F2)(bool c)
if ( __traits(compiles,F1().chain(F2())))
{
return only(true).repeat(c?1:0).map!(x=>F1()).join
.chain(only(true).repeat(c?0:1).map!(x=>F2()).join);
}
auto f(ulong n) {
return (n!=0uL).rangeFuncIf!(()=>only(100/n), ()=>only(0));
}
auto g(ulong n) {
return choose(n!=0uL,only(100/n),only(0));
}
void main()
{
writeln(f(2));
writeln(f(0));
writeln(g(2));
//writeln(g(0)); <---- runtime error
}
More information about the Digitalmars-d-learn
mailing list