Another switch suggestion.

Stewart Gordon smjg_1998 at
Fri Sep 1 10:58:45 PDT 2006

Fredrik Olsson wrote:
> As the switch syntax already allows for more funky stuff than C does, 
> that requires some kind of code to be inserted why not extend on it a 
> bit and allow for say:
> switch (foo) {
>   case ($ >= 'a' && $ <= 'z') || ($ >= 'A' && $ <= 'Z'):
>     doStuff();
>     break;
>   default:
>     doOtherStuff();
>     break;
> }
> Just as $ means "length of array" for slicing an array and such, why not 
> let $ mean "the value the current switch is testing for"?

What if you want to include the value being tested as an array index?

> And if the 
> case have a boolean expression instead of a constant than the first case 
> that evaluates to true should be run.

Why restrict switch to boolean expressions and constants?  Moreover, 
what about boolean constants - constants are still expressions, aren't 
they?  Before I got this far, I'd figured that if a '$' is present then 
it would compare it with true, otherwise it would compare the input 
value with the value of the case expression.

I'm not sure I like your idea really.  Moreover, suppose you have this:

     switch (qwert) {
         case $ > 42:
         case yuiop[69..$] > 105;

then what would make sense?

(a) to treat $ in the second case as being the value of qwert, and to 
pass if the expression evaluates to true?
(b) to treat $ in the second case as the length of yuiop, and because 
the whole thing is still a boolean expression, see if it's true (thereby 
not using qwert at all)?
(c) to treat $ in the second case as the length of yuiop, and notice 
that the expression doesn't depend on $ in its meaning of the switched 
value and therefore compare qwert with the boolean value of the expression?

Moreover, your code could just as easily be written

     if ((foo >= 'a' && foo <= 'z') || (foo >= 'A' && foo <= 'Z')) {
     } else {

OK, so foo might be a whole expression, which might have a side effect 
or be cumbersome to write out each time.  But it's probably just as 
efficient to assign the result to a variable first and use if statements 
as it would be to do what you're proposing.

> One of the few features I miss from Visual Basic :).
> And an even better syntax for the above example would naturally be:
> switch (foo) {
>   case $ in <'a'..'z', 'A'..'Z'>:

Why have the '$' at all for this syntax?  Or are you trying to propose a 
whole new expression syntax to be used in more than just cases?  Using 
'<' and '>' for anything but comparison operators is bound to lead to 
parsing complications.  That's why templates don't use this notation.


Version: 3.1
GCS/M d- s:-@ C++@ a->--- UB@ P+ L E@ W++@ N+++ o K-@ w++@ O? M V? PS- 
PE- Y? PGP- t- 5? X? R b DI? D G e++++ h-- r-- !y

My e-mail is valid but not my primary mailbox.  Please keep replies on 
the 'group where everyone may benefit.

More information about the Digitalmars-d mailing list