Type programming game

Basile B. b2.temp at gmx.com
Sun Oct 11 09:31:43 UTC 2020


On Saturday, 10 October 2020 at 23:42:46 UTC, Stefan Koch wrote:
> Hi,
>
> just now I came up with a nice game.
>
> 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 am looking forward to what you come up with.
>
> After a few submissions have been made I will post my type 
> function, which fulfills this task.
>
> Have a good day,
>
> Stefan

fully CTFE + using a map to solve uniquness. Naive, longish, but 
easy to understand I'd say as self-criticism... but I suppose 
that the final goal of this game is to show us an astonishing TF 
solution ;)

---
import std.algorithm;

string solveByMapping(T...)()
{
     string[] uniques;
     size_t[] indexes;
     size_t[] count;
     string result;

     static foreach (TT; T)
     {
         if (!uniques.canFind(TT.stringof))
             uniques ~= TT.stringof;
         indexes ~= uniques.length - 1;
     }
     count.length = uniques.length;
     static foreach (i, TT; T)
     {
         count[indexes[i]] += 1;
     }
     foreach(ref c; count)
     {
         if (c != 2 && c != 3)
             c = 0;
     }
     foreach(i, c; count)
     {
         if (!c)
             continue;
         result ~= (c == 3) ? " triple " : " twice ";
         result ~= uniques[i];
     }
     return result[1..$];
}

static assert (solveByMapping!(int, int, uint, uint, uint) == 
"twice int triple uint");
static assert (solveByMapping!(int, int, uint) == "twice int");
static assert (solveByMapping!(float, float, int, int, uint) == 
"twice float twice int");
---


More information about the Digitalmars-d mailing list