16

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?

2 Answers2

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}

enter image description here

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}

David Carlisle
  • 757,742
  • Do you know if it is possible to use for loop on comma separated list if parameter of \myfunc is another function. So: \def \someVar {a, b, c} then \myfunc{\someVar} In this case all variable is considered a one item – Dmytro Jul 09 '20 at 18:17
  • @Dmytro \expandafter\myFunc\expandafter{\someVar} – Qrrbrbirlbel Aug 13 '22 at 02:26