Original question
I would like to create a metacommand for creating new projection commands. Specifically, \newproj{\cmd}{<n>}{<m>} should create \cmd as a new command of <n> (mandatory) arguments that always expands to the <m>th argument.
For example, if we have \newproj{\fst}{2}{1} and \newproj{\snd}{2}{2}, then \fst{x}{y} should expand to x whereas \snd{x}{y} should expand to y.
Here is my attempt at this:
\documentclass{article}
\newcommand*{\newproj}[3]{%
\newcommand*#1[#2]{%
\expandafter#\expandafter##3%
}%
}
\newproj{\fst}{2}{1}
\newproj{\snd}{2}{2}
\begin{document}
\begin{tabular}{ll}
\verb^\fst{x}{y}^:& \fst{x}{y} \\
\verb^\snd{x}{y}^:& \snd{x}{y}
\end{tabular}
\end{document}
Unfortunately, this gives the error "Illegal parameter number in definition of \newproj.
<to be read again> \expandafter" How can I use a parameter as a function of some integer or metaparameter?
Extended question: indirection via a macro
A.Ellett and Hendrik Vogt suggest using \newcommand*#1[#2]{###3} because ## expands to #. This works perfectly if a positive integer is passed as #3 to \newproj! However, suppose that I pass a macro to \newproj as #3. How can I use expansion of a macro to dynamically select a parameter?
For example, the following should produce the correct results. However, it gives the error "Illegal parameter number in definition of \fst. <to be read again> \i".
\documentclass{article}
\newcommand*{\newproj}[3]{%
\newcommand*#1[#2]{%
\expandafter###3%
}%
}
\def\i{1}
\newproj{\fst}{2}{\i}
\newproj{\snd}{2}{2}
\begin{document}
\begin{tabular}{ll}
\verb^\fst{x}{y}^:& \fst{x}{y} \\
\verb^\snd{x}{y}^:& \snd{x}{y}
\end{tabular}
\end{document}



\expandafters:\newcommand*{\newproj}[3]{\newcommand*#1[#2]{###3}}does the job. – Hendrik Vogt Feb 21 '13 at 20:02\foreach \x/\y/\z in {fst/2/\i,snd/2/2}{<do something>}. – Ahmed Musa Feb 21 '13 at 21:43\newproj? – Henry DeYoung Feb 21 '13 at 21:47