Pattern matching example

Lutger lutger.blijdestijn at gmail.com
Sun Apr 4 08:18:59 PDT 2010


bearophile wrote:

> I'm not currently asking to implement pattern matching in D3 (as present
> for example in Scala), but it's positive to think how to solve similar
> problems in D2, because even if pattern matching is not available in D2,
> the problems it is asked to solve solve can be real.
> 
> Walter or Andrei has recently shown here a possible implementation idea,
> but I don't remember where the post is and what the implementation was. And
> it wasn't a small compilable program.

It was a subthread under the 'is D a cult' thread, this was the basic 
example:

foo(  v,
      (int i) { writeln("I saw an int ", i); },
      (string s) { writeln("I saw a string ", s); ),
      (Variant any) { writeln("I saw the default case ", any); }
    );


The criticism was that this only does matching on type. Matching on strings 
and integers should be done with case statements and other values with if-
else.

I don't have the time to implement this, but after some hacking I found that 
something like the following could be made to work, exploiting AA 
initializers.  I'm not sure how efficient it would be though:

void matcher(T, C...)(T value, C Cases)
{
    foreach( Case ; Cases)
    {
        static if ( is(typeof(Case.keys) == T[]))
        {
            if (value in Case)
            {
                auto fun = Case[value];
                fun(value);
            }
        }
    }
}


void main(string[] args)
{
    int i = 12;
    matcher(i,
          [ "aha": (string v) { writeln("I saw a string ", v); } ],
          [ 12   : (int i) { writeln("I saw an int ", i); } ] );

    string v = "aha";      
    matcher(v,
          [ "aha" : (string v) { writeln("I saw a string ", v); } ],
          [ 12    : (int i) { writeln("I saw an int ", i); } ] );
}



More information about the Digitalmars-d mailing list