1

Recently I discovered a piece of code (from ucharclasses) using three expansion-related macros \noexpand, \unexpanded and \expandafter:

\def\do#1{\noexpand\setTransitionsFor{#1}{####1}{####2}}
\def\doclass#1{
  \begingroup\edef\x{\endgroup
    \noexpand\newcommand
    \unexpanded\expandafter{\csname setTransitionsFor#1\endcsname}[2]%
    {\csname #1Classes\endcsname}}\x}
\ClassGroups

I can find some references about these macros, but I still don't understand what they are doing exactly. I'd like to know why they are necessary in the above piece of code, and why would we ever need four sharps as in ####1 and ####2.

Cyker
  • 667

1 Answers1

2

\do shows \noexpand and ##

\def\do#1{\noexpand\setTransitionsFor{#1}{####1}{####2}}

\edef\z{\do{abc}} \show\z

this shows

> \z=macro:
->\setTransitionsFor {abc}{##1}{##2}.
l.4 \show\z

So you see that in defining \z with \edef the csname \setTransitionsFor was prevented from being expanded by the \noexpand , #1 got replaced by the argument to \do which is abc here and ## got replaced by #

For the second macro, adding \show\x then running this fragment with pdflatex

\def\doclass#1{
  \begingroup\edef\x{\endgroup
    \noexpand\newcommand
    \unexpanded\expandafter{\csname setTransitionsFor#1\endcsname}[2]%
    {\csname #1Classes\endcsname}}%
    \show\x
    \x}

\doclass{abc}

produces

> \x=macro:
->\endgroup \newcommand \setTransitionsForabc [2]{\abcClasses }.
\doclass ...csname #1Classes\endcsname }}\show \x 
                                                  \x 
l.9 \doclass{abc}

? x

so after the \show the temporary macro \x will be executed and be equivalent to

\newcommand \setTransitionsForabc [2]{\abcClasses }

so the string abc that was passed to \doclass has been used to construct both the commandnames \setTransitionsForabc and \abcClasses

David Carlisle
  • 757,742