3
$\begingroup$

In C++ / C#, one can fall through multiple cases to execute one function instead of calling that function after each case.

For example,

switch (value)
{
   case 1:
   case 3:
   case 4:
       DoExercise(value);
       break;
   case 2:
       SkipLunch(value);
       break;
   case 5:
   default:
       GoHome();
       break;
}

Do we have a similar way to fall through multiple cases?

As I understand I need to do

Switch[value, 1, DoExercise[value], 3, DoExercise[value],4, DoExercise[value],
2, SkipLunch[value],
5, GoHome[],
_, GoHome[]]

Can I do something like

Switch[value, (1 or 4 or 3), DoExercise[value], 2, SkipLunch[value], _, GoHome[]]
$\endgroup$
7
$\begingroup$

Sometimes the answer is "try it and see!" In this case, the corrected syntax for the Or condition doesn't work.

test[value_] := 
  Switch[value, (1 || 4 || 3), DoExercise[value], 2, 
   SkipLunch[value], _, GoHome[]]


 Array[test, 10]

 (*{GoHome[], SkipLunch[2], GoHome[], GoHome[], GoHome[], 
  GoHome[], GoHome[], GoHome[], GoHome[], GoHome[]} *)

As noted by Xavier in comments, you could use Alternatives (| not ||):

test[value_] := Switch[value, (1 | 4 | 3), DoExercise[value], 
  2, SkipLunch[value], _, GoHome[] ]

Another option is to use the Which function:

test2[value_] := 
 Which[MemberQ[{1, 4, 3}, value], DoExercise[value], value == 2, 
  SkipLunch[value], True, GoHome[]]

 Array[test2, 10]

 (* {DoExercise[1], SkipLunch[2], DoExercise[3], DoExercise[4], 
   GoHome[], GoHome[], GoHome[], GoHome[], GoHome[], GoHome[]} *)
$\endgroup$
3
  • 2
    $\begingroup$ In case one would want to keep Switch, the correct syntax would be to use Alternatives rather than Or: test[value_] := Switch[value, (1 | 4 | 3), DoExercise[value], 2, SkipLunch[value], _, GoHome[]] works fine. $\endgroup$
    – user31159
    Oct 8 '15 at 4:58
  • $\begingroup$ Thanks Xavier, I completely forgot about Alternatives. I'll amend my answer. $\endgroup$
    – Verbeia
    Oct 8 '15 at 5:01
  • $\begingroup$ Thanks guys! I am surprised there is no such sample in Mathematica's document center, but then again, I should have tried as Verbeia suggested. $\endgroup$
    – Leonx
    Oct 13 '15 at 5:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.