14

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?

14

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.

|improve this answer|||||
11

LaTeX has a built in command for iterating over comma separated lists:

\documentclass{article}

\makeatletter
\newcommand\myfunc[1]{\@for\tmp:=#1\do{\func{\tmp}}}

\let\func\fbox

\begin{document}

\myfunc{a,b,c,d}

\end{document}
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.