Is there a nice way in Mathematica to express the equivalent of Switch where statements (not cases) fall through? Here is a toy example in C:
switch (n)
{
case 4: printf ("4");
/* fall through */
case 3: printf ("3");
/* fall through */
case 2: printf ("2");
/* fall through */
case 1: printf ("1");
break;
}
(In reality the statements would be computations, not just printf's.)
I've thought of two ways. One is to use Goto[] and Label[]:
ClearAll[trial1];
trial1[n_] := Module[
{one, two, three, four},
Goto[{one, two, three, four}[[n]]];
Label[four];
Print[4];
Label[three];
Print[3];
Label[two];
Print[2];
Label[one];
Print[1];
]
The other holds each statement in a list, takes the desired elements, and releases the holds:
ClearAll[trial2];
trial2[n_] := Module[
{lst},
lst = {
Hold[Print[4];],
Hold[Print[3];],
Hold[Print[2];],
Hold[Print[1];]
};
ReleaseHold[Take[lst, -n]];
]
Both work, but neither seems "clean" or Mathematica-like.
My question differs from this one where several cases fall through to the same statement.
Added later: Here is a sample. Calling the function with 3 results in the last three statements executing.
trial2[3]
(* 3 2 1 *)