Defining a new command, the output of which depends on an internal parameter

definitionmacros

Maybe someone can tell me how to define a new command in \LaTeX, which can take one mandatory value and another optional value (parameter) as input. In this case, depending on the value of the optional argument, the type of the output object should change.

Specifically in my case, I need to specify a command \dependSet(<arg>, <opt par>) to draw parentheses. in this case, depending on the presence / absence of the optional argument should change the output (presence / absence of a vertical line inside):

Function Output
\dependSet{x, y} enter image description here
\dependSet{x, y}{a} row

Accordingly, for usability it is important that the parameter comes after the arguments of the command, and it is selected with curly brackets, not square ones.

P.S.: Actually, it's a pity that LaTex uses a rather uncomfortable notation (which reeks of something like ALGOL 60) and does nothing to make it possible to define new commands in Python-like style.

Best Answer

Let's assume you don't want to type in (x,y) or (x,y\mid a) for some reasons. And there are good reasons not to: for instance, you might want or be required to change notation. A hardwired input would make the task very difficult.

The idea is to type in

\dependSet{x,y}
\dependSet{x,y|a}

but without impacting on the final output. The input is quite natural and avoids the complications of too many braces.

How do we do it? We can use \NewDocumentCommand and its \SplitArgument feature.

\documentclass{article}
%\usepackage{xparse} % uncomment for older versions of LaTeX

\NewDocumentCommand{\dependSet}{>{\SplitArgument{1}{|}}m}{%
  \dependSetAux#1%
}
\NewDocumentCommand{\dependSetAux}{mm}{%
  \IfNoValueTF{#2}{% no | found
    (#1)%
  }{% found |
    (#1\mid #2)%
  }%
}

\begin{document}

$\dependSet{x}+\dependSet{x,y}+\dependSet{x,y|a}$

\end{document}

enter image description here

Comments.

The command \dependSet passes its argument to \dependSetAux as two braced groups. If there is no | in the initial argument, the second braced group will be {-NoValue-} that can be tested as shown.

If you want to change the final formatting, act on \dependSetAux.

A possibly more efficient code, but less straightforward, would be

\NewDocumentCommand{\dependSetAux}{mm}{%
  (#1\IfValueT{#2}{\mid #2})%
}
Related Question