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 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?

share|improve this question
    
Please accept one of the given answers. Thanks in advance. –  Marco Daniel Dec 15 '11 at 19:26
add comment

4 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}
share|improve this answer
add comment

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}
share|improve this answer
add comment

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}

Conditional macro use

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).

share|improve this answer
    
Related link: why is the ifthen package obsolete –  Peter Grill Nov 3 '11 at 17:41
add comment

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}
share|improve this answer
add comment

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.