8

I need to make a simple conditional in a macro. If #1 is "1", "2", "3", "4", "5", or "6", then print Text: #1, otherwise, do nothing, even if it is empty. I tried this code:

\ifnum#1=1
    Text:~#1
\if

I cannot even get make it able to check if 1 is present. How can I check #1 is equal to "1", "2", "3", "4", "5", or "6"?

  • Is #1 definitely an integer, or does the answer need to cover the case where it's not? Can it be an integer expression (such as 10 - 6) and if so does that need to count? – Joseph Wright Apr 22 '12 at 11:24
  • Only \macro{1}, \macro{2}, \macro{3}, \macro{4}, \macro{5}, and \macro{6} should count as a match. Something like \macro{15} should not count as any match. Usually, the macro is empty, like \macro{}, I guess is why my code is getting confused. – Village Apr 22 '12 at 11:29
  • Should \macro{\really\wild\input} be taken into account? – egreg Apr 22 '12 at 12:49
12

In your comments you indicated that #1 can be empty

\ifnum#1=1
    Text:~#1
\if

would be an error in that case but a simple change to

\ifnum0#1=1
    Text:~#1
\if

will make an empty argument be Ok (and count as zero). beware that \macro{ 1} would then be an error as \ifnum0 1=1 does not work as 0 1 is not a valid number. It's possible to insert extra macros to remove spurious spaces if that is needed.

  \ifnum0#1>0
     \ifnum0#1<7
        Text:~#1
    \fi
  \fi
  • From the way the question is phrased, I'd interpret the comparison as essentially string-based (it has to be exactly as given). You could easily get rid of the spaces with \numexpr, or as you say using a macro-based approach. My worry with the \numexpr solution is that something like 1 + 1 would then be valid, but the question suggests it's not. – Joseph Wright Apr 22 '12 at 12:02
3

For a limited range of integers, with the other possibilities as blank or integer input, I would go with

\catcode`\@=11 %
\long\def\@firstoftwo#1#2{#1}
\long\def\@secondoftwo#1#2{#2}
\long\def\macro#1{%
  \ifnum 0#1 > 0 %
    \ifnum 0#1 < 7 %
      \expandafter\expandafter\expandafter\@firstoftwo
    \else
      \expandafter\expandafter\expandafter\@secondoftwo
    \fi
  \else
    \expandafter\@secondoftwo
  \fi
}

used as

\macro{}\TRUE\FALSE
\macro{0}\TRUE\FALSE
\macro{1}\TRUE\FALSE
\macro{6}\TRUE\FALSE
\macro{7}\TRUE\FALSE
1

I hope that I understood your question correctly:

\def\myempty{}
\def\mynumber#1{%
\if#1\myempty
\else
\ifnum#1>0
\ifnum#1<7
Text:~#1
\fi\fi\fi}
This is \mynumber{0} \mynumber{4} \mynumber{7}
\end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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