How extend command defined using SplitArgument so as to allow 4 arguments not just 2

macrosxparse

I have a command \cont used mainly in the form \cont{X, Y} and defined using \SplitArgument, as shown in the source below. How can I redefine (that is, extend the definition of)\cont so as to allow 4 arguments rather than 2, which get grouped in pairs as shown in the outout equation (2)?

Notice that I want to continue using a comma as separator when there are only 2 arguments, as in \cont{X, Y}. But I want to change the (main) separator to a semicolon when there are 4 arguments, while retaining commas as subsidiary separators, as in \cont{X, x; Y, y}.

\documentclass[fleqn]{memoir}
\usepackage{xparse}

\NewDocumentCommand{\cont}{ >{\SplitArgument{1}{,}} m }{\printcont#1}
\NewDocumentCommand{\printcont}{mm}{{\mathcal{C}}({#1}\IfValueT{#2}{, {#2}})}

\begin{document}

\noindent Equation~(\ref{one}) shows use of \verb!\cont! with 2 arguments, as in \verb!\cont{X, Y}!, with comma as separator:
\begin{equation}\label{one}
\cont{X, Y}
\end{equation}
 
\noindent How can we \emph{extend} the definition of \verb!\cont! so that\dots\\[6pt]
\mbox{}\qquad\verb!\cont{X, x; Y, y}! \\[6pt]
---with commas and a single semicolon as separators----gives the same result as equation~(\ref{two}), below?
\begin{equation}\label{two}
\mathcal{C}[(X, x), (Y, y)]
\end{equation}

\end{document}

extend def to allow 4 args not just 2

Best Answer

I'd issue the \mathcal{C} immediately and then pass control to another command that checks for a semicolon and takes the appropriate action.

\documentclass[fleqn]{memoir}
\usepackage{amsmath}

\NewDocumentCommand{\cont}{>{\SplitArgument{1}{;}}m}{%
  \mathcal{C}%
  \printcont#1%
}
\NewDocumentCommand{\printcont}{mm}{%
  \IfNoValueTF{#2}{%
    \conttwo{#1}%
  }{%
    [\conttwo{#1},\conttwo{#2}]%
  }%
}
\NewDocumentCommand{\conttwo}{>{\SplitArgument{1}{,}}m}{%
  \printconttwo#1%
}
\NewDocumentCommand{\printconttwo}{mm}{%
  (#1\IfValueT{#2}{,#2})%
}

\begin{document}

\begin{gather*}
\cont{X} \\
\cont{X, Y} \\
\cont{X;Y} \\
\cont{X,x;Y} \\
\cont{X, x;Y, y}
\end{gather*}

\end{document}

enter image description here

If you want to add \bigl and \bigr to the brackets with \cont*, then pass the argument throughout.

\documentclass[fleqn]{memoir}
\usepackage{amsmath}

\NewDocumentCommand{\cont}{s>{\SplitArgument{1}{;}}m}{%
  \mathcal{C}%
  \printcont{#1}#2%
}
\NewDocumentCommand{\printcont}{mmm}{%
  \IfNoValueTF{#3}{%
    \conttwo{#2}%
  }{%
    \IfBooleanT{#1}{\bigl}[%
    \conttwo{#2},\conttwo{#3}
    \IfBooleanT{#1}{\bigr}]%
  }%
}
\NewDocumentCommand{\conttwo}{>{\SplitArgument{1}{,}}m}{%
  \printconttwo#1%
}
\NewDocumentCommand{\printconttwo}{mm}{%
  ({#1}\IfValueT{#2}{, {#2}})
}

\begin{document}

\begin{gather*}
\cont{X} \\
\cont{X, Y} \\
\cont{X;Y} \\
\cont{X,x;Y} \\
\cont{X, x;Y, y} \\
\cont*{X,x;Y} \\
\cont*{X, x;Y, y}
\end{gather*}

\end{document}

enter image description here

Related Question