16

While trying to answer a question I came upon a problem with counters and I need some help. The idea is to collect answers to some numbered exercises, so the collected answers can be all typeset at some later point in the document; my approach was to use the collect package to, well, collect the answers:

\documentclass{scrartcl}
\usepackage{collect}

\definecollection{answers}

\makeatletter
\newenvironment{answer}
  {\@nameuse{collect}{answers}%
    {\par\medskip\noindent\textbf{Answer to~\theexercise}}%
    {\par}%
    {}%
    {}%
  }
  {\@nameuse{endcollect}}
\makeatother

\newcounter{exercise}
\newenvironment{ex}
  {\refstepcounter{exercise}\par\noindent This is exercise~\theexercise}
  {\par}

\begin{document}

\begin{ex}
\end{ex}
\begin{answer}
This is the answer to exercise 1 but it is numbered 3.
\end{answer}

\begin{ex}
\end{ex}
\begin{answer}
This is the answer to exercise 2 but it is numbered 3.
\end{answer}

\begin{ex}
\end{ex}
\begin{answer}
This is the answer to exercise 3 and it is numbered 3.
\end{answer}

\includecollection{answers}

\end{document}

However, as it was expected, using this approach, all the answers receive the number corresponding to the last value of the exercise counter and not the number associated to their corresponding exercise (see the image). How can this be solved?

enter image description here

Gonzalo Medina
  • 505,128

1 Answers1

12

You have to expand \theexercise before doing the write:

\documentclass{scrartcl}
\usepackage{collect}

\definecollection{answers}

\newcommand\mycollect[1]{%
  \collect{answers}
    {\par\medskip\noindent\textbf{Answer to~#1}}
    {\par}
    {}{}%
}

\newenvironment{answer}
  {\begingroup\edef\x{\endgroup\noexpand\mycollect{\theexercise}}\x}
  {\endcollect}

\newcounter{exercise}
\newenvironment{ex}
  {\refstepcounter{exercise}\par\noindent This is exercise~\theexercise}
  {\par}

\begin{document}

\begin{ex}
\end{ex}
\begin{answer}
This is the answer to exercise 1 but it is numbered 3.
\end{answer}

\begin{ex}
\end{ex}
\begin{answer}
This is the answer to exercise 2 but it is numbered 3.
\end{answer}

\begin{ex}
\end{ex}
\begin{answer}
This is the answer to exercise 3 and it is numbered 3.
\end{answer}

\includecollection{answers}

\end{document}

enter image description here

egreg
  • 1,121,712