I would like a new command: \myfunc{string}, where string is something like: "a,b,x,y,x" and the effect of the command should be the following:
\func{a}\func{b}\func{x}\func{y}\func{x}, where \func{} is another predefined function. How to do this?
Asked
Active
Viewed 5,182 times
16
user3058699
- 883
2 Answers
17
This is very easy with xparse:
\documentclass{article}
\usepackage{xparse}
\NewDocumentCommand{\myfunc}{ >{\SplitList{,}} m }{%
\ProcessList{#1}{\func}%
}
\NewDocumentCommand{\func}{m}{%
\fbox{#1} % a space follows
}
\begin{document}
\myfunc{a,b,c,x,y,z}
\end{document}

Note that \func can be defined in whatever way you like, also with \newcommand. What's important is that it has one argument.
You can also add code before \ProcessList{#1}{\func} and after it.
Note that you're not restricted to commas as separators, because you specify it at definition time.
Another advantage is that \SplitList automatically trims leading and trailing spaces around items, so the output from
\myfunc{ a , b,c ,x,y , z }
will be the same, contrary to other lower level approaches.
egreg
- 1,121,712
14
LaTeX has a built in command for iterating over comma separated lists:
\documentclass{article}
\makeatletter
\newcommand\myfunc[1]{@for\tmp:=#1\do{\func{\tmp}}}
\makeatother
\let\func\fbox
\begin{document}
\myfunc{a,b,c,d}
\end{document}
Thom Wiggers
- 129
David Carlisle
- 757,742
\expandafter\myFunc\expandafter{\someVar}– Qrrbrbirlbel Aug 13 '22 at 02:26