Basic pattern matching in C# 6

Idan Arye via Digitalmars-d digitalmars-d at puremagic.com
Fri Aug 15 05:01:58 PDT 2014


On Friday, 15 August 2014 at 10:03:39 UTC, bearophile wrote:
> A proposal for a basic pattern matching in C# 6:
>
> http://www.infoq.com/news/2014/08/Pattern-Matching
>
> But it's still rather limited:
>
>>Under the current draft specification, there is no support for 
>>range checks. This means you cannot write patterns such as “a 
>>is Location( > 0, 1 to 5, <= 10)”. Nor is there support for 
>>matching elements in a list or enumeration.<
>
> Bye,
> bearophile

Pattern matching will always be awkward in languages where the 
data types were not designed to be pattern-matched. In that 
regard, the main difference between languages like C# and D to 
languages like ML and Haskell is that in the former the order of 
fields is an implementation detail while in the later it's an 
actual part of the type's interface definition.

This is why the `is` operator is required in that C# proposal. In 
ML, when you write `datatype foo = Foo of int * int * int`, the 
actual representation of the type is a tuple of 3 integers - the 
order matters, and it defines both the constructor and the 
pattern matching.

In C# you can write:

     class Foo
     {
         private int X{get; set;}
         private int Z{get; set;}
         private int Y{get; set;}

         public Foo(int x, int y, int z)
         {
             this.x = X;
             this.y = Y;
             this.z = Z;
         }

         public static bool operator is(Foo foo,
                 out int z,
                 out int y,
                 out int x)
         {
             x = foo.x;
             y = foo.y;
             z = foo.z;
         }
     }

     Debug.Assert(new Foo(1, 2, 3) is Foo(3, 2, 1);

And note that both the constructor and the `is` operator are 
different from the order described in memory.

Scala solved it nicely with case classes, which get translated to 
regular JVM classes but generate the structuring-destructuring 
code automatically and consistently, but Scala can do it because 
it's type declaration syntax was designed to support the 
functional style - trying to do that with C# class declaration 
style will just be awkward.

Maybe if C#(and maybe also D?) had their own version of case 
classes?


More information about the Digitalmars-d mailing list