Pattern matching in D

Walter Bright newshound1 at digitalmars.com
Mon Mar 8 03:35:56 PST 2010


retard wrote:
>> I've thought more than once about adding that, but it just seems
>> pointless. I've never run into a use case for it. If you do run into
>> one,
>>
>>      if (ar == [1,2,3]) ...
>>      else if (ar == [1,2,4]) ...
>>      else if (ar == [1,3,2]) ...
>>
>> will work just fine.
> 
> The same can be said about matching integer values:
> 
>>      if (ar == 1) ...
>>      else if (ar == 2) ...
>>      else if (ar == 3) ...

I don't agree, because switching on integer values is commonplace, and 
switching on array literals pretty much never happens.

(Note: switching on floating point values is worse than useless, as 
floating point computations rarely produce exact results, and supporting 
such a capability will give a false sense that it should work.)


> I guess the point is just to unify many kinds of cases.
> 
> class Foo
> class Bar : Foo { void doBarMethod() {} }
> class Bar2 : Foo { void doBar2Method() {} }
> 
> if (cast(Bar)foo)
>   (cast(Bar)foo).doBarMethod();
> else if (cast(Bar2)foo)
>   (cast(Bar2)foo).doBar2Method();
> else
>   writefln("Oh no!")


I have to say, if you find code written that way, you're doing OOP wrong.


> foo match {
>   case b: Bar => b.doBarMethod
>   case b: Bar2 => b.doBar2Method
>   case _ => println("Oh no!")
> }
> 
> (1, (1,2)) match {
>   case (1, (1, _)) => println("nice tuple")
>   case _ =>
> }
> 
> def main(args: Array[Byte]) =
>   args(0) match {
>     case "-help" => println("Usage: ...")
>     case "-moo" => println("moo")
>   }

D already supports string switches.



More information about the Digitalmars-d mailing list