2

Is it possible to define two macros with the same command but expecting different number of arguments? Then, based on the number of arguments the user provides, one or the other is used. Here is an example:

\newcommand{\com}[1]{\text{com}({#1},r_{#1})}
    
\newcommand{\com}[2]{\text{com}({#1},{#2})}
3

2 Answers 2

3

Here's something that might work. You can expect and/or handle any number of entries in the single mandatory argument. Each can be accessed via the appropriate

\clist_item:Nn \l_tmpa_clist {item number goes here}.

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
    
\NewDocumentCommand\mycommand{m}{
  \int_case:nnTF {\clist_count:n{#1}}{
        % if a single item, do stuff with it
        {1}{you~entered~\clist_item:nn {#1} {1}}
        % if two items, do stuff with them
        {2}{you~entered~\clist_item:nn {#1}{1}~and~\clist_item:nn{#1}{2}}
        % if more items etc.
   }
   {} % <-if any of the cases above match, do this, here nothing
   {\msg_error:nn {mycommand}{wrong~number~of~arguments~to~mycommand}}%<- if no cases match, do something, here issue an error.
}

\ExplSyntaxOff

\begin{document}

\mycommand{blue}

\mycommand{blue,green}

\mycommand{blue,green,yellow}
    
\end{document}
1
  • @egreg yes that would be more simple, not sure why I set the clist.
    – Scott H.
    Dec 29, 2022 at 20:54
2

No, but you can do

\NewDocumentCommand{\com}{mo}{%
  \operatorname{com}(#1,\IfNoValueTF{#2}{r_{#1}}{#2})%
}

and call either

\com{x}

or

\com{x}[y]

If r_ should be used in either case, the definition can be even simpler

\NewDocumentCommand{\com}{mO{#1}}{%
  \operatorname{com}(#1,r_{#2})%
}

Actually, it is possible. It's up to you if you want to break all syntax conventions of LaTeX and be prepared to get weird output now and then.

\documentclass{article}
\usepackage{amsmath}

\ExplSyntaxOn

\NewDocumentCommand{\com}{}
 {
  \peek_regex_replace_once:nn
   { ( \{ [^\}]* \} )* } % search all braced groups
   { \c{lorenzo_com:n} \{\0\} } % pass them as single argument to \lorenzo_com:n
 }

\cs_new_protected:Nn \lorenzo_com:n
 {
  \operatorname{com}
  \int_case:nnF { \tl_count:n { #1 } }
   {
    {0}{}
    {1}{\__lorenzo_com:n #1}
   }
   {\__lorenzo_com:nn #1}
 }

\cs_new_protected:Nn \__lorenzo_com:n { (#1,r\sb{#1}) }
\cs_new_protected:Nn \__lorenzo_com:nn { (#1,#2) }

\ExplSyntaxOff

\begin{document}

$\com{x}+y$

$\com{x}{y}+z$

$\com{x} {y}+z$

$\com{x}{y}{z}+u$

\end{document}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .