[Tex/LaTex] Conditional cases expression

conditionals

How can I create a command \if with 1 argument, namely #1,

\if{#1=1}{symbol1}...{#1=n}{symboln}

that returns symbol1, when #1 is 1, …, and returns symboln, when #1 is n, and returns nothing, when #1 isn't 1,...,n?

For example, I'd like to use the command

\if{#1=1}{\mapsto}{#1=2}{\mapsfrom}{#1=3}{\rightarrow}

when I'm defining a larger command.

Best Answer

For simple integer comparisons, TeX provides \ifcase:

\ifcase<integer>
  % Case 0
\or
  % Case 1
\or
...
\else
  % Optional
\fi

So you can define a wrapper such as

\newcommand\myswitch[1]{%
  \ifcase#1\relax
    \ValueWasZero
  \or
    \ValueWasOne
  \or
    \ValueWasTwo
  ...
  \else
     \OtherCases
  \fi
}

Here, you start from the 0 case and work upward: often you'll see \ifcase#1\relax\or with no 0 case at all. You can use as many \or statements as you like, depending on how many numbers you need. The \else is optional, and is used if you want 'otherwise do this' functionality.

By the way, don't define \if: this is a TeX primitive which you should not change!

Related Question