The following is a high-level (possibly not entirely accurate) model of how TeX \expandafter
works.
An important realization in learning TeX expansion is the difference between expansion and execution/actions (an expansion is merely a transformation of an input sequence of TeX tokens into an output sequence of tokens). This point is covered in Part 5 of the excellent article series on \expandafter
on Overleaf: How does \expandafter work: A detailed macro case study.
-
Initial expression
\ea1\ea2\ea3\a\ea4\b\c
-
\ea1
expanded-
\ea2
saved -
\ea3
expanded-
\a
saved -
\ea4
expanded-
\b
saved -
\c
expanded
-
-
-
-
Expression after previous expansion:
\ea2\a\b<expansion of \c>
-
\ea2
expandeda.
\a
savedb.
\b
expanded -
Expression after previous expansion:
\a<expansion of \b><expansion of \c>
-
\a
expanded -
Expression after previous expansion:
<expansion of \a><expansion of \b><expansion of \c>
Given arbitrary \b
, \c
, \d
(macros without arguments), for example
\def\b{\c\c}
\def\c{*}
\def\d{\b\c}
define \a
so that its replacement text consists of \b
fully expanded, \c
not expanded, and \d
expanded exactly once
. That is, with the above definitions thereplacement text of \a
should be
**\c\b\c
You may not use \the
or \noexpand
in the solution.
Many solutions are documented in 1 Expansion in Around The Bend, but they are all significantly longer than the following:
\edef\next#1#2{\def#1{\b#2}}
\expandafter\next\expandafter\a\expandafter{\expandafter\c\d}
After the above, \meaning\a
prints out
macro:->**\c \b \c
as intended. The way it works is that the first \expandafter
triggers an expansion which results in the expansion of \d
as
\next\a{\c\b\c}
thus accomplishing the expansion of \d
exactly once.