2

Is this possible?

\documentclass{article}
\usepackage{xparse,amsmath}
\NewDocumentCommand{\myfunc}{O{} m O{+} m}{
    % some dark sorcery
}
\begin{document}
\[
\myfunc[a]{x,y}{2,3} % should return ax^2 + ay^3
\]
\end{document}
mjc
  • 745

3 Answers3

1
\documentclass{article}
\usepackage{xparse,amsmath}
\NewDocumentCommand{\myfunc}{O{} m O{+} m}{
    \zz{#1}#2,\relax{#3}#4,\relax
}
\def\zz#1#2,#3\relax#4#5,#6\relax{%
#1#2^{#5}
\if$#3$\expandafter\zzstop\else#4\fi
\zz{#1}#3\relax{#4}#6\relax
}
\def\zzstop#1\relax#2\relax{}
\begin{document}
\[
\myfunc[a]{x,y}{2,3} % should return ax^2 + ay^3
\]
\end{document}

enter image description here

David Carlisle
  • 757,742
1
\documentclass{article}
\usepackage{xparse,amsmath,listofitems}
\NewDocumentCommand{\myfunc}{O{} m O{+} m}{
  \readlist\bases{#2}%
  \readlist\exponents{#4}%
  \foreachitem\z\in\bases[]{%
    \ifnum\zcnt=1\else#3\fi
    #1\z^{\exponents[\zcnt]}%
  }%  
}
\begin{document}
\[
\myfunc[a]{x,y}{2,3} % should return ax^2 + ay^3
\]
\end{document}

enter image description here

1

Alternatively, you can use the Expl3 coding style to manage this:

\ExplSyntaxOn
\NewDocumentCommand{\myfunc}{O{} m O{+} m}{
  \seq_set_from_clist:Nn \l_tmpa_seq {#2}
  \seq_set_from_clist:Nn \l_tmpb_seq {#4}
  \cs_set:Npn \__mapper ##1##2 {\__sep #1##1^{##2}}
  \cs_set:Npn \__sep {\cs_set:Npn \__sep {#3}}
  \seq_mapthread_function:NNN \l_tmpa_seq \l_tmpb_seq \__mapper
}
\ExplSyntaxOff

(I spent a bunch of time trying to write a kernel extension to do a zip of two sequences which would have taken two sequences and a map function to create a new sequence, but then I stumbled on \seq_mapthread_function:NNN which kind of does what I was looking for, but without outputting to a sequence. I may continue with that later if only to sharpen my expl3 chops. It would also have allowed my to replace the last three lines with something like

\seq_set_zip \__tmp_seq \l_tmpa_seq \l_tmpb_seq {#1##1^{##2}}
\seq_use:Nn \__tmp_seq { #3 }

which would be arguably clearer).

I don't know if the creation of the \__mapper is strictly necessary, but it seems to be the case that the lack of \seq_mapthread_function:NNn dictates it.

Don Hosek
  • 14,078