Improvement to switch-case statement

Yigal Chripun yigal100 at gmail.com
Fri Jan 2 13:32:20 PST 2009


Stewart Gordon wrote:
> Yigal Chripun wrote:
> <snip>
>> IMO, either the switch statement should remain the low level
>> (effiecient) construct as in C, or replaced by a general mechanism of
>> pattern matching. your solution is kinda between the two above options
>> and I don't see the point of it.
>
> What would a "general mechanism of pattern matching" involve, and how
> would it replace switch? Would it replace if as well?
>
>> I'd personally prefer pattern matching to be added to D and the switch
>> to be deprecated and eventually removed from the language.
>
> I'd personally prefer my proposal from years ago to be taken seriously:
> http://www.digitalmars.com/d/archives/22722.html
>
> ISTM silly to improve switch but at the same time keep it restricted to
> the same old arcane syntax.
>
> Stewart.

I have several idea on this, nothing finished though:

the only reason for switch in the first place is an optimization in the 
compiler, besides that, there is no need for it at all and everything 
can be done with a bunch of if statements.

we basically need a way to group several if/case statements together and 
make them refer the same variable.

here's a first attempt:

match (value) {
   case(1) foo();
   case(2..4) { foo(); case(3) foo3(); bar(); continue; }
   case(5) {...}
   case() {...} // this is the default case
}

to get the old switch behavior of fall through you use continue. and 
cases can be nested. I'd say that making cases overlap should be 
compiler error. the only way it makes sense to me to have overlapping 
cases is in concurrent code but than the code will need to be marked for 
that anyway.

another related thing,  the catch list is also a switch. so instead of 
the current:
try {
// put code here
} catch (ExceptionA e) {
} catch (ExceptionB e) {
} catch (ExceptionC e) {}

we can extend "case" like this:

try {
// put code here
} catch (e) {
   case(ExceptionA) handleA(e);
   case(ExceptionB) handleB(e);
   case(ExceptionC) handleC(e);
   case()           handleDefault(e);
}

also, some thought should be spent on getting rid of the ternary op 
syntax since it interferes with other things that could be added to the 
language (nullable types, for instance)



More information about the Digitalmars-d mailing list