11

Consider the following document:

\documentclass{article}
\usepackage{polynomial}

\begin{document}
\def\a{-3}
\def\b{-2}
\def\c{-4}
\[
\polynomial{\a,\b,\c}\quad\polynomial{-3,-2,-4}
\]
\end{document}

As can be seen in the result

enter image description here

the first \polynomial produces extra + signs in front of negative coefficients, most probably due to late expansion of \a, \b, and \c. How can this be prevented?

Edit:

The solution provided

\begingroup\edef\x{\endgroup\noexpand\polynomial{\a,\b,\c}}\x

fails in a moving argument:

\documentclass{article}
\usepackage{polynomial}

\begin{document}
\def\a{-3}
\def\b{-2}
\def\c{-4}
\begin{figure}
\caption{$\begingroup\edef\x{\endgroup\noexpand\polynomial{\a,\b,\c}}\x$}
\end{figure}
\end{document}

What modifications are required in this case?

This question appeared while providing an answer to Parameters in a caption.

0

3 Answers 3

9

You can redefine \polynomial to expand its argument:

\documentclass{article}
\usepackage{polynomial,xparse}

\ExplSyntaxOn
\cs_set_eq:NN \gonzalo_poly:n \polynomial
\cs_generate_variant:Nn \gonzalo_poly:n { x }
\RenewDocumentCommand{\polynomial}{m}
 {
  \gonzalo_poly:x { #1 }
 }
\ExplSyntaxOff

\begin{document}


\begin{figure}
\def\a{-3}
\def\b{-2}
\def\c{-4}

X
\caption{$\polynomial{\a,\b,\c}$}
\end{figure}
\end{document}
1
  • Ah, I like this. It's perfectly in line with my intention to learn expl3 syntax. Thanks! Jul 25, 2015 at 22:33
7

You need to force expansion of the arguments before \polynomial. A typical approach would be

\documentclass{article}
\usepackage{polynomial}

\begin{document}
\def\a{-3}
\def\b{-2}
\def\c{-4}
\[
\begingroup\edef\x{\endgroup\noexpand\polynomial{\a,\b,\c}}\x
\quad\polynomial{-3,-2,-4}
\]
\end{document}

assuming that \a, \b and \c can be taken to be fully expandable (as here).

7

You can declare a robust command so it is safe in a caption:

\documentclass{article}
\usepackage{polynomial}
\DeclareRobustCommand\xpolynomial[1]{%
\edef\next{\noexpand\protect\noexpand\polynomial{#1}}\next}


\begin{document}

\listoftables

\begin{table}
\def \a{-3}
\def\b{-2}
\def \c{-4}

\caption{$\xpolynomial{\a,\b,\c}$}

\end{table}

zzzz

\end{document}

Or to do it locally as requested in comments

\documentclass{article}
\usepackage{polynomial}



\begin{document}

\listoftables

\begin{table}
\def \a{-3}
\def\b{-2}
\def \c{-4}
\def\xpolynomial#1#2{%
\edef#1{\noexpand\protect\noexpand\polynomial{#2}}}
\xpolynomial\thispoly{\a,\b,\c}

\caption{$\thispoly$}

\end{table}

zzzz

\end{document}
2
  • 1
    Thanks, David. Let's say I don't want to declare it robust from the beginning. Would it be possible to \protect what needs to be protected in \edef\next{\noexpand\protect\noexpand\polynomial{#1}}\next} so it works in captions? Jul 26, 2015 at 0:00
  • @GonzaloMedina updated answer Jul 26, 2015 at 9:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .