2

I try to use nested if-then-else conditions:

\documentclass[10pt]{article}
\usepackage{ifthen}

\newcommand{\printTrueOrFalseA}[1]{%
   \ifthenelse{\equal{#1}{true}}{true}{false}%
}

\newcommand{\True}{true}
\newcommand{\False}{false}

\newcommand{\printTrueOrFalseB}[1]{%
   \ifx#1\True true\else false\fi%
}

\begin{document}
\printTrueOrFalseA{\printTrueOrFalseA{true}} % produces an error
\printTrueOrFalseB{\printTrueOrFalseB{true}} % produces the unexpected  result "false"
\end{document}

When I use the \ifthenelse command, my code produces an error:

! Argument of \equal has an extra }.<inserted text>\par \printTrueOrFalseA{\printTrueOrFalseA{true}}
! Paragraph ended before \equal was complete.<to be read again>\par \printTrueOrFalseA{\printTrueOrFalseA{true}}

I would expect the result true in both cases. Why does it not work as I would expect?

anja
  • 21

2 Answers2

2

Your \printTrueOrFalseA{\printTrueOrFalseA{true}} becomes

\ifthenelse{\equal{\printTrueOrFalseA{true}}{true}{true}{false}

but the argument to \equal is illegal, because \ifthenelse is not fully expandable, hence you get an error.

Your \printTrueOrFalseB{\printTrueOrFalseB{true}} becomes

\ifx\printTrueOrFalseB{true}\True true\else false\fi

which compares \printTrueOrFalseB with {, returning false; the tokens true}\True true vanish because they constitute the “true branch” for \ifx. This expands to false\fi and then \fi vanishes, leaving just “false” as printout.

egreg
  • 1,121,712
1

here is how you could do it (without \ifthenelse)

\documentclass[10pt]{article}

\makeatletter
\newcommand{\printTrueOrFalseC}[1]{%
   \romannumeral
   \if\pdfstrcmp{#1}{true}0%
        \expandafter\@firstoftwo
   \else\expandafter\@secondoftwo
   \fi
   {\z@ true}{\z@ false}%
}

\makeatother
\begin{document}

\huge
\printTrueOrFalseC{\printTrueOrFalseC{\printTrueOrFalseC{\printTrueOrFalseC{\printTrueOrFalseC{\printTrueOrFalseC{true}}}}}}

\printTrueOrFalseC{\printTrueOrFalseC{\printTrueOrFalseC{\printTrueOrFalseC{\printTrueOrFalseC{\printTrueOrFalseC{True}}}}}}% test checks for "true", not "True"
\end{document}

enter image description here