Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

up vote 11 down vote accepted

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

share|improve this answer
    
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 at 1:14
    
@GonzaloMedina I've simplified the code –  egreg Feb 19 at 1:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.