Here's an option using sequences, it could probably be made a little more compact as the code from the two helper macros is almost identical.
I'm not an expert so take my advice with a grain of salt but I would just stick with using sequences
. They require an extra line of code here and there, but the additional options that they provide are well worth it.
\documentclass{article}
\usepackage{xparse}
\usepackage{siunitx}
\ExplSyntaxOn
\NewDocumentCommand{\sumofsquares}{ m o }
{
\IfNoValueTF {#2}
% if optional is missing call this
{\sum_of_squares:n {#1}}
% if not, then call this
{\sum_of_squares:nn {#1}{#2}}
}
\cs_new_protected:Npn \sum_of_squares:n #1
{
% does what the name suggests, set a sequence from the clist
\seq_set_from_clist:Nn \l_tmpa_seq {#1}
% applies final arg to each element of second seq and stores result in first seq
\seq_set_map:NNn \l_tmpb_seq \l_tmpa_seq {(##1)^2}
% \seq_use puts the items from the seq back in the input with "+" as a separator
\sqrt{\seq_use:Nnnn \l_tmpb_seq {+}{+}{+}}
}
\cs_new_protected:Npn \sum_of_squares:nn #1 #2
{
% same as above, but with the addition of units
\seq_set_from_clist:Nn \l_tmpa_seq {#1}
\seq_set_map:NNn \l_tmpb_seq \l_tmpa_seq {(\SI{##1}{#2})^2}
\sqrt{\seq_use:Nnnn \l_tmpb_seq {+}{+}{+}}
}
\ExplSyntaxOff
\begin{document}
$\sumofsquares{2,3,-4}$\par\medskip
$\sumofsquares{2,3,-4}[m/s]$
\end{document}
Here's a slightly shorter (and less clear) example using clist
s. The same method could have been used to shorten the code above.
\documentclass{article}
\usepackage{xparse}
\usepackage{siunitx}
\ExplSyntaxOn
\NewDocumentCommand{\sumofsquares}{ m O{} }
{
\sum_of_squares:nn {#1}{#2}
}
\cs_new_protected:Npn \sum_of_squares:nn #1 #2
{
\tl_if_empty:nTF {#2}
{
\clist_set:Nn \l_tmpa_clist {#1}
\sqrt{(\clist_use:Nnnn \l_tmpa_clist {)^2+(} {)^2+(} {)^2+(} )^2 }
}
{
\clist_set:Nn \l_tmpa_clist {#1}
\sqrt{(\clist_use:Nnnn \l_tmpa_clist {\,\si{#2})^2+(} {\,\si{#2})^2+(} {\,\si{#2})^2+(} \,\si{#2})^2}
}
}
\ExplSyntaxOff
\begin{document}
$\sumofsquares{2,3,-4}$\par\medskip
$\sumofsquares{2,3,-4}[m/s]$
\end{document}
sequence
is just a linear array of items. It has a first item, a second item and so on. To make one, you just take a list of things whose distinct elements are separated by some specific character, say;
and use\seq_set_split:Nnn {name}{separator}{list}
.expl3
then provides functions for working with them. Think of aclist
as asequence
whose separator is a comma. Functionally, I don't think there's much difference between them.sequence
's are more versatile,clist
's maybe shorten some syntax. – Scott H. Nov 11 '12 at 3:33\sumofsquares[m/s]{2,3,4}
or\sumofsquares{2,3,4}{m/s}
(with no optional argument). – Joseph Wright♦ Nov 11 '12 at 8:35