Is it possible to filter variadics?
TheFlyingFiddle via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Nov 3 16:03:14 PST 2015
On Tuesday, 3 November 2015 at 23:41:10 UTC, maik klein wrote:
> Is it possible to filter variadics for example if I would call
>
> void printSumIntFloats(Ts...)(Ts ts){...}
>
> printSumIntFloats(1,1.0f,2,2.0f);
>
> I want to print the sum of all integers and the sum of all
> floats.
>
>
> //Pseudo code
> void printSumIntFloats(Ts...)(Ts ts){
> auto sumOfInts = ts
> .filter!(isInteger)
> .reduce(a => a + b);
> writeln(sumOfInts);
> ...
> }
>
> Is something like this possible?
It is possible: I don't think that reduce works on tuples but you
could do something like this.
import std.traits, std.meta;
void printsumIntFloats(Ts...)(Ts ts)
{
alias integers = Filter!(isInteger, Ts);
alias floats = Filter!(isFloatingPoint, Ts);
alias int_t = CommonType!(integers);
alias float_t = CommonType!(floats);
int_t intres = 0;
float_t floatres = 0;
foreach(i, arg; ts)
{
static if(isInteger!(Ts[i]))
intres += arg;
else
floatres += arg;
}
writeln(intres);
writeln(floatres);
}
More information about the Digitalmars-d-learn
mailing list