You are here: Home / Przedsięwzięcia/Projects / TeX Pearls / 2007 Pearls / marcin-wolinski / src / fullexpandafter.tex


TeX document icon fullexpandafter.tex — TeX document, 2 KB (2084 bytes)

File contents


\title{Multiple expansions triggered with a single
\author{Marcin Woli\'nski}


This pearl (coded on October 18, 1996) is the most useless one I could
think of.  Nonetheless it is an example of a really curious expansion
of macros.

Let us imagine that we have a list of non-space tokens and we want to
assign this list to a token register without expanding the tokens and
in reversed order.  Here is a simple macro that reverses a list in an
expand-only way:


Now we can write
and \TeX\ will respond with writing \texttt{gfedcba} on the terminal.

To put the result of reversing the list \verb|abc\foo def\bar ghi| in
a token register we do the following:
\toks0=\expandafter{\if0\reverse{abc\foo def\bar ghi0}}\fi
With the use of \verb|\expandafter| we introduce a single expansion to
the region where expansion is suppressed.  The token being expanded is
the \verb|\if|.  To expand an \verb|\if| \TeX\ needs to find next two
non-expandable tokens to compare them.  The first token is \texttt{0},
but then \TeX\ sees the macro \verb|\reverse|.  So the macro gets
expanded.  An interesting feature of \verb|\reverse| is that no
non-expandable tokens are emitted until the list is fully reversed.
So only then \TeX\ stops expansion.  The first non-expandable token
\TeX\ will see is the second \texttt{0}, which we have devilishly
inserted at the end of the list.  At this point the condition turns
out to be true and the next tokens get assigned as contents to the
token register.


%%% Local Variables: 
%%% mode: latex
%%% TeX-master: t
%%% End: 

Document Actions