Type programming game

Timon Gehr timon.gehr at gmx.ch
Sun Oct 11 00:47:26 UTC 2020


On 11.10.20 01:42, Stefan Koch wrote:
> 
> Write a template/function takes a sequence of types, and "returns" a 
> string.
> Whenever the same type appears twice in the sequence directly after the 
> previous occurrence,
> append ("double " ~ name_of_type) to the string.
> Whenever it appears three times, append ("triple " ~ name_of_type).
> 
> So (int, int, uint, uint, uint) would return "double int triple uint")
> Or (char, char, wchar, dchar, dchar) would return "double char double 
> dchar"

I guess the canonical solution is something like this:

alias Seq(T...)=T;
template Group(T...){
     static if(T.length==0) alias Group=Seq!();
     else static if(T.length==1) alias Group=Seq!(1,T[0]);
     else{
         alias R=Group!(T[1..$]);
         static if(is(T[0]==R[1])) alias Group=Seq!(R[0]+1,R[1..$]);
         else alias Group=Seq!(1,T[0],R);
     }
}
template solve(T...){
     template rec(G...){
         static if(G.length==0) enum rec="";
         else{
             enum r=rec!(G[2..$]);
             enum s=G[1].stringof~(r.length?" ":"")~r;
             static if(G[0]==2) enum rec="double "~s;
             else static if(G[0]==3) enum rec="triple "~s;
             else enum rec=r;
         }
     }
     alias solve=rec!(Group!T);
}

static assert(solve!(int,int,uint,uint,uint)=="double int triple uint");
static assert(solve!(char,char,wchar,dchar,dchar)=="double char double 
dchar");


More information about the Digitalmars-d mailing list