Pattern matching in D
Simen kjaeraas
simen.kjaras at gmail.com
Mon Mar 8 04:36:16 PST 2010
Walter Bright <newshound1 at digitalmars.com> wrote:
>> 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.
Which means that D supports array switches (untested code):
switch( (string)foo ) {
case (string)[1,2,3]: doSomething( );
case (string)[3,2,1]: doSomethingElse( );
}
Might require some tweaking, but I believe this would work. Not saying
it's a good idea, though.
As for structs:
switch ( foo.toHash( ) ) {
case S(1,2,3).toHash( ): doSomething( );
case S(3,2,1).toHash( ): doSomethingElse( );
}
If toHash is CTFE-able. Just as untested, and might not work at all.
--
Simen
More information about the Digitalmars-d
mailing list