4

The following code does not compile if I don't have the extra braces around the entries of the matrix, and I don't know why. Can I modify \switcher to obviate the need for these extra braces?

\documentclass{article}
    \usepackage{amsmath}

    \newcommand{\switcher}[2][]
    {
        \ifx&#1&%
            #2
        \else
            #1
        \fi
    }

\begin{document}

\[
    \begin{bmatrix}
        {\switcher{2}} \\
        {\switcher[1]{2}}
    \end{bmatrix}
\]

\end{document}
Troy
  • 13,741
Stirling
  • 1,419
  • What is switcher supposed to do exactly? – Werner Dec 18 '13 at 02:54
  • I only used switcher as a simple example of a function whose behavior changes depending on whether or not the optional argument is specified. My actual function does something different obviously, but I thought the details distracted from the question. – Stirling Dec 18 '13 at 04:23

1 Answers1

4

If you're attempting to condition between whether or not the optional argument is empty, the following is a better approach:

enter image description here

\documentclass{article}
\usepackage{amsmath}% http://ctan.org/pkg/amsmath

\makeatletter
\def\ifemptyarg#1{%
  \if\relax\detokenize{#1}\relax % https://tex.stackexchange.com/q/308/5764
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi}
\makeatother

\newcommand{\switcher}[2][]{%
  \ifemptyarg{#1}
    {#2}% Empty optional argument
    {#1}% Non-empty optional argument
}

\begin{document}

\[
  \begin{bmatrix}
    \switcher{2} \\
    \switcher[1]{2}
  \end{bmatrix} \qquad
  \begin{bmatrix}
    \switcher{a} & \switcher[b]{c} & \switcher[]{d} & \switcher{e} \\
    \switcher[f]{} & \switcher{} & \switcher[]{} & \switcher[g]{h}
  \end{bmatrix}
\]

\end{document}

The above \ifemptyarg is taken from Different command definitions with and without optional argument, while other gems also exist in Check for empty macro argument.

Werner
  • 603,163