static switch/pattern matching

John via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 25 03:39:09 PDT 2016


On Saturday, 25 June 2016 at 09:12:12 UTC, Lodovico Giaretta 
wrote:
> On Saturday, 25 June 2016 at 09:07:19 UTC, Lodovico Giaretta 
> wrote:
>>
>> Instead of passing functions to match!, pass pairs of 
>> arguments, like this:
>>
>>     match!(T,
>>         int, writeln("Matched int"),
>>         is(T : SomeObject), writeln("Derives from SomeObject");
>>     );
>>
>> Now, in the implementation, foreach pair of arguments, if the 
>> first member is a type that matches your target, perform that 
>> branch; otherwise, if the first member is a boolean value, and 
>> it is true, perform the branch.
>
> Of course I meant:
>
>      match!(T,
>          int, () {writeln("Matched int");},
>          is(T : SomeObject), () {writeln("Derives from 
> SomeObject");}
>      );
>

Thanks for the help, both. This appeared to work, until I 
realised the lambda isn't static:

   void match(T, cases...)() {
     static if (cases.length == 1) cases[0]();
     else static if (cases.length > 2) {
       static if (is(typeof(cases[0]) == bool)) {
         static if (cases[0]) cases[1]();
         else match!(T, cases[2 .. $]);
       }
       else static if (is(T == cases[0])) cases[1]();
       else match!(T, cases[2 .. $]);
     }
   }

   void test(T)(T value) {
     int i;
     string s;
     match!(T,
       int, () => i = value,
       string, () => s = value
     );
   }

   test(1);
   test("A string");

The compiler complains about not being able convert an int to a 
string and vice versa.


More information about the Digitalmars-d-learn mailing list