[Tex/LaTex] new command with cases / conditionals / ‘if… then’s

conditionalsmacros

Suppose I want to define a command, say, \tree with, say, two arguments. I would like \tree to do different things depending on what my first argument is. For example,

if #1 = a, then return $\sqrt{#2}$

if #1 = b, then return "Hi"

Is it possible to realise the above pseudocode? If so, how can I?

Best Answer

You can also use \IfEqCase from the xstring package which can easily be extended to add more cases:

enter image description here

Notes:

  • Besides being able to easily extend to more cases, this also has the benefit that it will produce a \PackageError if an unknown option is passed in.

Code:

\documentclass{article}
\usepackage{xstring}

\newcommand{\tree}[2]{%
    \IfEqCase{#1}{%
        {a}{$\sqrt{#2}$}%
        {b}{Hi}%
        % you can add more cases here as desired
    }[\PackageError{tree}{Undefined option to tree: #1}{}]%
}%
\begin{document}
\tree{a}{4}

\tree{b}{4}

%\tree{c}{4}
\end{document}
Related Question