2

I am trying to collect certain counter values in a list of tokens. Here is my naive attempt:

\documentclass{article}

\newtoks\list
\list={}

\def\addtolist#1{\global\list=\expandafter{\the\list #1}}

\newcounter{counter}
\def\countertolist{\expandafter\addtolist{\arabic{counter}}}

\begin{document}

\stepcounter{counter}
\stepcounter{counter}
\countertolist
\stepcounter{counter}
\stepcounter{counter}
\countertolist

\the\list

\end{document}

I would like the result to be 24 but it is 44. It seems that in the definition of \countertolist the \arabic{counter} is not 'expanded enough' (i.e. not expanded when \countertolist is used). What is the right definition?

2

The main reason is that \arabic{counter} is not expanded enough. This can be changed to \expandafter\addtolist\expandafter{\the\c@counter} to force the expansion.

\documentclass{article}

\newtoks\list
\list={}

\def\addtolist#1{\global\list=\expandafter{\the\list #1}}

\newcounter{counter}
\makeatletter
\def\countertolist{\expandafter\addtolist\expandafter{\the\c@counter}}
\makeatother

\begin{document}

\stepcounter{counter}
\stepcounter{counter}
\countertolist
\stepcounter{counter}
\stepcounter{counter}
\countertolist

\the\list

\end{document}
  • 1
    maybe it should be pointed out that \newtoks\list may be a rather unfortunate choice (try adding something like \begin{center} or \begin{itemize} ... to the above document :-) – Frank Mittelbach Mar 30 '18 at 10:28
  • @FrankMittelbach: Thanks for suggestion -- I would not use a token list here at all, but that's the choice of the O.P. – user31729 Mar 30 '18 at 10:33
  • that too, but that is a choice of the OP as you say. However redefining list means he wasn't aware of what he overwrites and that might just cause the next question afterwards – Frank Mittelbach Mar 30 '18 at 11:09
  • @FrankMittelbach: I will update with a usual \xdef\foo{\foo ...} method or something what the \@cons approach does with counter lists, for example – user31729 Mar 30 '18 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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