I’m a fan of factorization and hate code repetition. So I was trying to define a macro which defines for me all the common mathematical sets commands (\C, \N, etc.) and made a recursive function inspiring of \slowRomannumeral p. 24 from these TeX and LaTeX programmation notes.
So I did this first:
\def\defsets#1{\defnextset #1@}
\def\defnextset#1{\ifx @#1 \else
\expandafter\newcommand\csname #1\endcsname{\mathbb{#1}}
\expandafter\defnextset
\fi}
\defsets{RDNZQC}
But I soon realised that I needed something alike for my math operators, exactly the same but just with \DeclareMathOperator instead of \newcommand and without \mathbb, so I defined a \defset command and tried to make my main macro high-order:
\newcommand{\defset}[1]{\expandafter\newcommand\csname #1\endcsname{\mathbb{#1}}}
\def\defsets#1{\defnext\defset #1@}
\def\defnext#1#2{\ifx @#2 \else
#1#2\relax
\expandafter\defnext#1
\fi}
\defsets{RDNZQC}
And I checked a lot of things: I put a \relax otherwise for an unkown reason it tries to redefine expandafter, the first \newcommand does work, #1#2 should work, and using \def instead of \newcommand* to define \defset I get the following error:
ERROR: Missing \endcsname inserted.
--- TeX said ---
<to be read again>
\let
l.68 \defsets{RDNZQC}
and adding an \expandafter makes the same as the actual current code with \newcommand* (and all the same combinations with it): an infinite loop.
So how to make this code work? so I can just make a \defop and do the same thing for my math operators and some code tricks with each operator command between braces (since this currently works for single characters actually).


\defnextsetto be\defnext(which is used but not defined) – David Carlisle 18 hours ago