Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I want to define two versions of the command \Set, depending if I provide one or two parameters. I.e. like this:

\newcommand{\Set}[1]{\bigl\{ #1 \bigr\}}
\newcommand{\Set}[2]{\bigl\{ #1 \bigm| #2 \bigr\}}

But that doesn't work. It complains about the redefinition of the command.

share|improve this question

1 Answer 1

up vote 15 down vote accepted

You can't "overload" macros in TeX like functions in other programming languages.

You can either define the macro to use a normal optional argument for one of the two parameters or define a special macro which looks ahead if a opening brace follows. The xparse package can help you defining one:

\documentclass{article}

\usepackage{amsmath}
\usepackage{xparse}

\NewDocumentCommand\Set{mg}{%
    \ensuremath{\bigl\{ #1 \IfNoValueTF{#2}{}{\bigm| #2} \bigr\}}%
}

\begin{document}

\[
\Set{A}{B}
\Set{A}
\]

\end{document}

Here the m in the definition stand for mandatory argument and the g for optional argument delimited by a TeX group, i.e. {}.

share|improve this answer
    
I'd probably use G{} in the argument specification, then do the \IfNoValueTF test inside the \ensuremath, including #2 in all cases (as this will be fine with an empty default). –  Joseph Wright Mar 16 '11 at 15:23
    
Thanks @Joseph, I'm a beginner with xparse. But the "#2 in all cases` doesn't work because there is still \bigm| which must not be included in the first case. –  Martin Scharrer Mar 16 '11 at 15:28
    
Thanks, perfect! And that doesn't actually seem to be so complicated, why would you suggest not to use it? –  Albert Mar 16 '11 at 15:32
    
@Martin: Fair point, but you could stick to g and so use \IfNoValueF{#2}{\bigm| #2}. –  Joseph Wright Mar 16 '11 at 15:33
    
@Albert: I didn't say don't use it, I said defining such macros isn't that easy. But I had more the manual definition in mind. The xparse package simplifies things very much. –  Martin Scharrer Mar 16 '11 at 15:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.