3

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[]]
Leonx
  • 413
  • 2
  • 9

1 Answers1

7

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[]} *)
Verbeia
  • 34,233
  • 9
  • 109
  • 224
  • 2
    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. –  Oct 08 '15 at 04:58
  • Thanks Xavier, I completely forgot about Alternatives. I'll amend my answer. – Verbeia Oct 08 '15 at 05:01
  • 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. – Leonx Oct 13 '15 at 05:51