Switch

Switch[expr,form1,value1,form2,value2,]
evaluates expr, then compares it with each of the formi in turn, evaluating and returning the valuei corresponding to the first match found.

DetailsDetails

  • Only the valuei corresponding to the first formi that matches expr is evaluated. Each formi is evaluated only when the match is tried.
  • If the last formi is the pattern _, then the corresponding valuei is always returned if this case is reached.
  • If none of the formi match expr, the Switch is returned unevaluated.
  • Switch has attribute HoldRest.
  • You can use Break, Return, and Throw in Switch.

ExamplesExamplesopen allclose all

Basic Examples  (2)Basic Examples  (2)

Process Boolean value to 1 or 0, giving a message and defaulting to 0 when not Boolean:

In[1]:=
Click for copyable input
In[2]:=
Click for copyable input
In[3]:=
Click for copyable input
Out[3]=

Give a suggested symbolic transformation for an expression:

In[1]:=
Click for copyable input
In[2]:=
Click for copyable input
Out[2]=

Try the transformation:

In[3]:=
Click for copyable input
Out[3]=
Introduced in 1988
(1.0)
Translate this page: