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?
- 1,028
- 19,767
6 Answers
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}
- 95,681
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 03 '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}
- 223,288
With functional package you can write this:
\documentclass{article}
\usepackage{functional}
\newcommand\M[2]{%
\StrIfEqTF{#1}{#2}{\Result{[#1]}}{\Result{[#1,#2]}}%
}
\begin{document}
Here is \M{2}{3}. Also, \M{2}{2} and \M{5}{1}.
\end{document}
- 10,932
In OpTeX, we can use expandable \isequal macro:
\def\M#1#2{\isequal{#1}{#2}\iftrue #1\else #1,#2\fi}
Test: \M{2}{2}. \M{1}{3}.
\bye
- 74,238