我有一个名为的命令\commandone
,它输出
测试。
我使用创建了它\newcommand\commandone{test}
我想要第二个命令,它接受一个整数输入,并根据输入的整数重复\commandtwo{}
调用第一个命令。因此,如果,输出将变为“\commandone
\commandtwo{3}
测试测试测试
答案1
答案2
看看 David Kastrup 的\replicate
宏:
http://www.gust.org.pl/projects/pearls/2005p/david-kastrup/bachotex2005-david-kastrup-pearl3.pdf
\documentclass{article}
\newcommand\replicate[2]{%
\ifnum#1>0 #2%
\expandafter\replicate\expandafter{\number\numexpr#1-1}{#2}%
\fi
}%
\newcommand\commandone{test}
\newcommand\commandtwo[1]{\replicate{#1}{\commandone}}
\begin{document}
\commandone
\commandtwo{3}%
\end{document}
\replicate
这里有这样一个变体,在任何情况下,在/\commandtwo
击中两次后你都会得到结果\expandafter
:
\documentclass{article}
\newcommand\UDfirstoftwo[2]{#1}
\newcommand\UDsecondoftwo[2]{#2}
\newcommand\replicate[2]{%
\romannumeral0\replicateb{#1}{#2}{}%
}%
\newcommand\replicateb[3]{%
\ifnum#1>0 \expandafter\UDfirstoftwo\else\expandafter\UDsecondoftwo\fi
{\expandafter\replicateb\expandafter{\number\numexpr#1-1}{#2}{#3#2}}%
{ #3}%
}%
\newcommand\commandone{test}
\newcommand\commandtwo[1]{%
\romannumeral\expandafter\UDsecondoftwo\replicate{#1}{\commandone}%
}
\begin{document}
\commandone
\commandtwo{3}%
\expandafter\expandafter\expandafter\def
\expandafter\expandafter\expandafter\test
\expandafter\expandafter\expandafter{\replicate{4}{\commandone}}
\texttt{\meaning\test}
\expandafter\expandafter\expandafter\def
\expandafter\expandafter\expandafter\testb
\expandafter\expandafter\expandafter{\commandtwo{5}}
\texttt{\meaning\testb}
\end{document}
这是一个没有使用 ϵ-TeX-extensions/without 的变体\numexpr
:
\documentclass{article}
\newcommand\UDfirstoftwo[2]{#1}
\newcommand\UDsecondoftwo[2]{#2}
\newcommand\replicate[1]{%
\romannumeral0\expandafter\replicateA
\expandafter{\romannumeral\number\number#1 000}%
}%
\newcommand\replicateA[2]{\replicateB{#2}{}#1\relax}
\newcommand\replicateB[3]{%
\if#3m\expandafter\UDfirstoftwo\else\expandafter\UDsecondoftwo\fi
{\replicateB{#1}{#2#1}}{ #2}%
}%
\newcommand\commandone{test}
\newcommand\commandtwo[1]{%
\romannumeral\expandafter\UDsecondoftwo\replicate{#1}{\commandone}%
}
\begin{document}
\commandone
\commandtwo{3}%
\expandafter\expandafter\expandafter\def
\expandafter\expandafter\expandafter\test
\expandafter\expandafter\expandafter{\replicate{4}{\commandone}}
\texttt{\meaning\test}
\expandafter\expandafter\expandafter\def
\expandafter\expandafter\expandafter\testb
\expandafter\expandafter\expandafter{\commandtwo{5}}
\texttt{\meaning\testb}
\end{document}