Generalrecursive use of \newcommand?

LaTeX specific issues not fitting into one of the other forums of this category.
Post Reply
fergal
Posts: 2
Joined: Tue Aug 04, 2009 2:19 am

recursive use of \newcommand?

Post by fergal »

I have a slightly advanced, and mostly pedagogical, question about using variables to define new commands in Latex.

Suppose I define a new command
\newcommand{\abbreviate}[2]{ #2 (#1)}

In the text, \abbreviate{USSR}{Union of Soviet Socialist Republics} will appear as "Union of Soviet Socialist Republics (USSR)"

However, that's a lot to type, so I'd prefer to be able to define \ussr to do the same thing, and then \usa to expand to 'United States of America (USA)', and so forth. What I really want to do is to be able to say

Code: Select all

\abbreviate{USSR}{Union of Soviet Socialist Republics}
\abbreviate{USA}{United States of America }
and then in the text I could just type \USA and \USSR. What I tried was this:

Code: Select all

\newcommand{\abbreviate}[2]{
\newcommand{\#1}{#2 (#1)}
}
But latex complains about \#1 and I can't quite figure out what sequence of characters to replace it with to get the desired effect.

I know there's a package out there that will do this for me, but as I said this is mostly pedagogical -- I'm trying to take my first murky steps into Latex programming. Any help appreciated.

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

sommerfee
Posts: 503
Joined: Mon Apr 09, 2007 4:20 pm

recursive use of \newcommand?

Post by sommerfee »

fergal wrote: \newcommand{\#1}{#2 (#1)}
Use

Code: Select all

\expandafter\newcommand\csname#1\endcsname{#2 (#1)}
instead.

HTH,
Axel
fergal
Posts: 2
Joined: Tue Aug 04, 2009 2:19 am

Re: recursive use of \newcommand?

Post by fergal »

Thanks, that did the job. I didn't know about \csname, I'll have to go read up on it.
Post Reply