# A problem with counters

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?

-

## 1 Answer

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}


-
Ah, thank you very much. I knew it was an expansion problem, but couldn't solve it. I need to study expansion more. –  Gonzalo Medina Feb 19 '14 at 1:14
@GonzaloMedina I've simplified the code –  egreg Feb 19 '14 at 1:23