[Tex/LaTex] Newcommand with optional argument and ifthenelse

macros

I would like to define a new command comp with two arguments where the second (and last) argument is optional, using 'ifthenelse'. I tried :

\newcommand{\comp}[2]{%
  \ifthenelse{\isempty{#2}}%
    {{#1}^{c}}% if #2 is empty
    {#2 \backslash #1}% if #2 is not empty
}

but \comp{Y}{X} gives Y\X instead of X\Y as wanted and \comp{Y} gives Y\ instead of the result of Y^c as wanted.

Best Answer

Optional arguments are usually set first and specified in brackets [] rather than braces {}.

With your code, if you type $\comp{Y}=Z$, the second argument is taken to be =, because of how TeX decides what the argument to a command is. Indeed, with

\newcommand{\comp}[2]{...}

the required arguments are two.

In my opinion, the optional argument should be the first, so you read

\comp[X]{Y}        \comp{Y}

as “the complement in X of Y” or “the complement of Y” respectively.

How to define that?

\usepackage{xifthen}

\newcommand{\comp}[2][]{\ifthenelse{\isempty{#1}}{#2^c}{#1\setminus#2}}

or

\usepackage{xparse}

\NewDocumentCommand{\comp}{om}{\IfNoValue{#1}{#2^c}{#1\setminus#2}}