Pattern matching via switch?

aliak something at something.com
Sat Mar 14 20:52:30 UTC 2020


On Saturday, 14 March 2020 at 19:04:28 UTC, 12345swordy wrote:
> I.E.
>
> switch (object)
>     case Type1 t1:
>     case Type2 t2:
>     case Type3 t3:

You can use the sumtype package 
(https://code.dlang.org/packages/sumtype):

alias T = SumType!(Type1, Type2, Type3);

T(object).match!(
     (Type1 t1) => "t1",
     (Type2 t2) => "t2",
     (Type3 t3) => "t3",
);


Or you can make a quick template like:

template switch_(funs...) {
     auto switch_(T)(auto ref T t) {
         static foreach (fun; funs) {
             static if (is(typeof(fun(T.init)))) {
                 return fun(t);
             }
         }
     }
}

struct A {}
struct B {}
struct C {}

void main()
{
     auto a = C();
     a.switch_!(
         (A _) => "a",
         (B _) => "b",
         (C _) => "c",
     ).writeln;
}

The template above is a quick fix and will have some holes 
though. Off the top of my head if more than one lambda "fits" 
there'll be problems.



More information about the Digitalmars-d-learn mailing list