Pattern matching in D
retard
re at tard.com.invalid
Mon Mar 8 00:59:07 PST 2010
Sun, 07 Mar 2010 22:05:19 -0800, Walter Bright wrote:
> BCS wrote:
>> I think what retard was asking was what types are legal as the argument
>> for a switch?
>>
>> IIRC the list is: all the arithmetic types and the string types.
>>
>> The value pattern matching that is being asked for would allow just
>> about anything that has a compile time literal syntax:
>>
>> void fn(int[] ar)
>> {
>> switch(ar)
>> {
>> case [1,2,3]: ... break;
>> case [1,2,4]: ... break;
>> case [1,3,2]: ... break;
>> }
>>
>> }
>
> 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 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!")
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")
}
More information about the Digitalmars-d
mailing list