# How to make a “condition” in a macro?

I would like to make a macro with two parameters which return a text. For instance, I want \M{1}{5} to return [1,5], and \M{2}{2} to return [2] (because the two arguments are the same). So I need to have a "check" or condition in my macro to see if the two parameters are the same and perform different executions... How do I implement this "if" in a macro?

-
Please accept one of the given answers. Thanks in advance. –  Marco Daniel Dec 15 '11 at 19:26

To complete the list I want to present the package etoolbox. If you are loading biblatex the package etoolbox will be loaded automatically.

\documentclass{article}
\usepackage{etoolbox}%
\newcommand{\M}[2]{%
\ifstrequal{#1}{#2}%
{[#1]}% #1 = #2 -> [#1]
{[#1,#2]}% [#1,#2]
}
\begin{document}
Here is \M{2}{3}. Also, \M{2}{2} and \M{5}{1}.
\end{document}

-

if that are all numbers then you can use \Mnum instead of \Mall

\documentclass{article}
\def\Mnum#1#2{[\ifnum#1=#2\relax #1\else#1,#2\fi]}
\def\Mall#1#2{[\def\tempA{#1}\def\tempB{#2}\ifx\tempA\tempB#1\else#1,#2\fi]}
\begin{document}

\Mnum{1}{5} \Mnum{2}{2}

\Mall{1}{5} \Mall{2}{2}
\end{document}

-

Using a more upper-level approach, the xifthen package provides a variety of conditional macros. Read the package documentation for more information about this. In your case, you could use

\documentclass{article}
\usepackage{xifthen}% http://ctan.org/pkg/xifthen
\newcommand{\M}[2]{%
\ifthenelse{\equal{#1}{#2}}%
{[#1]}% #1 = #2 -> [#1]
{[#1,#2]}% [#1,#2]
}
\begin{document}
Here is \M{2}{3}. Also, \M{2}{2} and \M{5}{1}.
\end{document}


In general, care should be taken when defining single-letter macros/control sequences, since (La)TeX defines a number of these for use in regular formatting (like \b for bar and \c for cedilla, to name a couple).

-
Related link: why is the ifthen package obsolete –  Peter Grill Nov 3 '11 at 17:41

Here is a solution using the xstring package. It has the advantage that it will compare numerical values, so that \M{2}{2.0} yields [2] (the first arg). If you want strict text equality use \IfStrEq instead of \IfEq.

\documentclass{article}
\usepackage{xstring}
\newcommand{\M}[2]{%
\IfEq{#1}{#2}%
{[#1]}% they are equal
{[#1,#2]}% not equal
}
\begin{document}
Here is \M{2}{3}. Also, \M{2}{2.0} and \M{5}{1}.
\end{document}

-