2

I'm trying to make a macro such that I give it arguments like this

\sqrtnorm{x,y,z}

such that it expands to,

\sqrt{x^2+y^2+z^2}

I'm trying (for no special reason) doing this with \@for command, this is what I've attempted

   \makeatletter
    \newcommand\sqrtnorm[1]{
        \sqrt{
    \@for\levar:=#1\do{
        {\levar}^2+}
        }
    }
    \makeatother
     

It's perfect in every way, except that there is a little + hanging around at the end. Is there a way to solve this?

1
  • Also, yeah, I kinda solved it now, by inverting the position of the + and just treating the first case as special. But maybe there is still a way to solve it by really considering the last case scenario?
    – Rainb
    May 16, 2021 at 7:11

2 Answers 2

3

Instead of appending a + I prepend a macro \@tempa, which defines itself as +. In this way at the first term the definition is executed, and only from the second term the + appears.

\documentclass{article}

\makeatletter
\newcommand*{\sqrtnorm}[1]{%
   \def\@tempa{\def\@tempa{+}}%        
   \sqrt{%
      \@for\levar:=#1\do{\@tempa{\levar}^2}%
    }%
}
\makeatother

\begin{document}

\[
\sqrtnorm{x,y,z}
\]

\end{document}

enter image description here

I've added a couple of % to hide the end of line. That's not crucial here because the macro appears in math mode, but it's not a bad idea either (and saves token memory).

2

With expl3:

\documentclass{article}
\usepackage{amsmath}

\ExplSyntaxOn
\NewDocumentCommand{\sqrtnorm}{m}
 {
  % make a sequence from the argument
  \seq_set_from_clist:Nn \l_tmpa_seq { #1 }
  % add ^2 to every item
  \seq_set_map:NNn \l_tmpb_seq \l_tmpa_seq { ##1^2 }
  % deliver the sequence with + between items
  \sqrt{\seq_use:Nn \l_tmpb_seq { + }}
 }
\ExplSyntaxOff

\begin{document}

$\sqrtnorm{x,y,z}$

\end{document}

enter image description here

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.