Use `\(…\)` in `algpseudocode`

algorithmicxalgpseudocodeinline()robust-commands

Is there a way to use the newer \(...\) math syntax in arguments for any commands from algpseudocode (algorithmicx)? The documentation and virtually any other tutorial uses the TeX-primitive $...$.

MWE:

\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{document}

\begin{algorithm}
    \begin{algorithmic}
        \For{\(i \gets 0\) to \(n\)}   % breaks
            \State \Call{Foo}{\(i\)}   % breaks
        \EndFor
    \end{algorithmic}
\end{algorithm}

\end{document}

Best Answer

I get no error from \For{\(i \gets 0\) to \(n\)}. But the error comes from \Call{Foo}{\(i\)} because \Call eventually becomes

#1#2->\textproc {#1}\ifthenelse {\equal {#2}{}}{}{(#2)}

and \equal{#2} fails when it is passed something that contains LaTeX robust commands, because it attempts doing full expansion.

You can fix this.

\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}

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


\begin{document}

\begin{algorithm}
    \begin{algorithmic}
        \For{\(i \gets 0\) to \(n\)}
            \State \Call{Foo}{\(i\)}
        \EndFor
    \end{algorithmic}
\end{algorithm}

\end{document}

enter image description here

Or, more efficiently,

\algrenewcommand\Call[2]{%
  \textproc{#1}%
  \if\relax\detokenize{#2}\relax\else(#2)\fi
}

There are other two places that might need such fix, so a complete version should be

\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}

%%% fix for usage of \ifthenelse
\newcommand{\algparenthesize}[1]{%
  \if\relax\detokenize{#1}\relax\else(#1)\fi
}
\algdef{SE}[PROCEDURE]{Procedure}{EndProcedure}[2]
 {\algorithmicprocedure\ \textproc{#1}\algparenthesize{#2}}
 {\algorithmicend\ \algorithmicprocedure}
\algdef{SE}[FUNCTION]{Function}{EndFunction}[2]
 {\algorithmicfunction\ \textproc{#1}\algparenthesize{#2}}
 {\algorithmicend\ \algorithmicfunction}
\algrenewcommand\Call[2]{\textproc{#1}\algparenthesize{#2}}
%%% end fix

\begin{document}

\begin{algorithm}
    \begin{algorithmic}
        \For{\(i \gets 0\) to \(n\)}
            \State \Call{Foo}{\(i\)}
        \EndFor
    \end{algorithmic}
\end{algorithm}

\end{document}