尝试构建命令\sol
并\solutions
在练习环境中使用它们。命令必须按以下方式工作:
\begin{exercises}
\exer text for exercise 1\sol{solutionA}
\exer text for exercise 2\sol{solutionB}
\exer text for exercise 3
\begin{subexerc}
\sexer text for subexercise 3.a.\sol{solutionC}
\sexer text for subexercise 3.b.\sol{solutionD}
\end{subexerc}
\end{exercises}
环境定义如下:
\newcounter{exercise}
\def\theexercise{\arabic{exercise}.}
\newenvironment{exercises}
{\begin{list}{\theexercise}{} }
{\end{list}
Solutions\par\solutions}
\def\exer{\refstepcounter{exercise}\item}
\newcounter{subexer}[exercise]
\def\thesubexer{\alph{subexer}.}
\newenvironment{subexerc}
{\begin{list}{\thesubexer}{} }
{\end{list}
\def\sexer{\refstepcounter{subexer}\item}
我尝试过这些定义:
\def\solutions{}
\makeatletter
\def\sol#1{%
\ifnum\value{subexer}=0
\g@addto@macro\solutions{\par\noindent\theexercise\ #1}%
\else
\g@addto@macro\solutions{\theexercise\thesubexer\ #1\ }%
\fi
}
\makeatother
但我得到了:
1. text for exercise 1 2. text for exercise 2 3. text for exercise 3 a. text for exercise 3.a b. text for exercise 3.b Solutions 3. solutionA 3. solutionB3.b. solutionC 3.b. solutionD
...我正在尝试:
1. text for exercise 1 2. text for exercise 2 3. text for exercise 3 a. text for exercise 3.a b. text for exercise 3.b Solutions 1. solutionA 2. solutionB 3.a. solutionC 3.b. solutionD
发生了什么事?它就像计数器一样exercise
,subexer
始终具有其最后值!
答案1
问题似乎是您将宏\theexercise
和添加到\thesubexer
了\solutions
,而不是当时的值。因此,在排版时,引用当时的当前值,当然,这是最后使用的值:
% Wrong:
\def\sol#1{%
\ifnum\value{subexer}=0
\g@addto@macro\solutions{\par\noindent\theexercise\ #1}%
\else
\g@addto@macro\solutions{\theexercise\thesubexer\ #1\ }%
\fi
}
此时您需要将其展开并添加展开后的值。为此,请使用\edef
临时宏,然后使用\expandafter
s 进行展开:
% Correct:
\def\sol#1{%
\begingroup
\ifnum\value{subexer}=0
\edef\@tempa{\noexpand\par\noexpand\noindent\theexercise}%
\expandafter\g@addto@macro\expandafter\solutions\expandafter{\@tempa\ #1}%
\else
\edef\@tempa{\theexercise\thesubexer}%
\expandafter\g@addto@macro\expandafter\solutions\expandafter{\@tempa\ #1\ }%
\fi
\endgroup
}