0

I have a new command which has optional parameters: depending on whether the parameter is empty or not, I would like the display to be different. When there is only one test, I manage it without problem but when there are several tests, I do not find how to proceed.

with the 3 parameters: display H(1)(2)(3) with 2 parameters (the 3rd is empty): display (1)(2) with a single parameter (the 2 and 3 are empty): display H(1)

Nicolas
  • 1,023
  • 1
    You provided no test code and your question is not clear, do you mean optional params, \foo, \foo[1], \foo[1][2], \foo[1][2][3] so you need a test if the option used, or three mandatory, but possibly empty arguments \foo{1}{2}{} ? – David Carlisle Mar 08 '23 at 22:31

3 Answers3

1

I hope this helps you.

The ifthen package can create conditional statements in LaTeX. Have a look at the following example where you can see how to define a command with three optional arguments that display different outputs depending on which arguments are empty:

\usepackage{ifthen}
\newcommand{\mycommand}[3][]{%
  \ifthenelse{\equal{#1}{}}{}{H}%
  \ifthenelse{\equal{#1}{}}{}{(#1)}%
  \ifthenelse{\equal{#2}{}}{}{(#2)}%
  \ifthenelse{\equal{#3}{}}{}{(#3)}%
}

This command will display H(#1)(#2)(#3) if all three arguments are provided, (#1)(#2) if only the first two arguments are provided, and H(#1) if only the first argument is provided. Is this what you were looking for?

scd
  • 774
1

Maybe, you want to do this:

\def\H#1#2#3{H\ifx&#1&\else (#1)\ifx&#2&\else (#2)\ifx&#3&\else (#3)\fi\fi\fi}

\H{a}{}{} % prints H(a)

\H{a}{b}{} % prints H(a)(b)

\H{a}{b}{c} % prints H(a)(b)(c)

\bye

wipet
  • 74,238
0

It seems somewhat superfluous to use multiple optional arguments, since their optionality switches to being mandatory once you need to use more. Unless, of course, you change the syntax.

The LaTeX3 interface to macros using \NewDocumentCommand allows for easily negotiating (multiple) optional arguments using o for [] arguments (or d<token><token> for a specific <token><token> pair). Testing is done using \IfValueTF{<arg>}{<true>}{<false>} (or more simply if nothing needs to be done when nothing is supplied, \IfValueT{<arg>}{<true>}).

enter image description here

\documentclass{article}

% \mycommandA uses the default [] for optional arguments \NewDocumentCommand{\mycommandA}{ o o o }{% \mathrm{H} \IfValueT{#1}{(#1) \IfValueT{#2}{(#2) \IfValueT{#3}{(#3)}}} } % \mycommandB uses () for optional arguments \NewDocumentCommand{\mycommandB}{ d() d() d() }{% \mathrm{H} \IfValueT{#1}{(#1) \IfValueT{#2}{(#2) \IfValueT{#3}{(#3)}}} }

\begin{document}

$\mycommandA[a]$

$\mycommandA[a][b]$

$\mycommandA[a][b][c]$

$\mycommandB(a)$

$\mycommandB(a)(b)$

$\mycommandB(a)(b)(c)$

\end{document}

Werner
  • 603,163