[Tex/LaTex] LaTeX Math Mode in algorithmic environment

algorithmicxmath-mode

The following code works fine:

\documentclass{article}
\usepackage{algpseudocode,amsmath}

\begin{document}
\begin{algorithmic}[1]
\State \Call{MergeSort}{$T(1,\dotsc,n)$}
\end{algorithmic}
\end{document}

However, if I replace $...$ with \(...\), I get an error for some reason. So the following code does not work:

\documentclass{article}
\usepackage{algpseudocode,amsmath}

\begin{document}
\begin{algorithmic}[1]
\State \Call{MergeSort}{\(T(1,\dotsc,n)\)}
\end{algorithmic}
\end{document}

I thought $...$ and \(...\) are equivalent. Why can this be happening? Thank you.

Best Answer

The \Call macro uses \ifthenelse, which has a very handy feature: it allows combining tests with propositional logic connectives (called \AND and \OR) with parentheses for the stating the precedence. Here's the catch! The symbols for these parentheses are \( and \). So the presence of \( and \) in the second argument of \Call (that is used in an \ifthenelse{\equal{#2}{}} test during processing if \Call) confuses TeX, because at the time of this evaluation \( and \) aren't the math formulas delimiters, but rather the “propositional logic parentheses”.

So, use $.

Alternative solution:

\documentclass{article}
\usepackage{algpseudocode,amsmath,xifthen}

\algrenewcommand\Call[2]{\textproc{#1}\ifthenelse{\isempty{#2}}{}{(#2)}}%

\begin{document}

\begin{algorithmic}[1]
\State \Call{MergeSort}{\(T(1,\dotsc,n)\)}
\end{algorithmic}
\end{document}

This works because xifthen introduces a new \isempty test that doesn't interpret its argument. Of course also other algpseudocode macros would need similar treatment.