pgf icon indicating copy to clipboard operation
pgf copied to clipboard

ifthenelse evaluates both branches

Open hmenke opened this issue 4 years ago • 4 comments

Brief outline of the bug

ifthenelse always evaluates both branches, regardless of the condition. It should short-circuit and only evaluate the branch that is actually taken.

Minimal working example (MWE)

\documentclass{article}
\usepackage{pgfmath}
\begin{document}
\pgfmathprint{ifthenelse(1 == 1, 1, 1/0)}
\pgfmathprint{ifthenelse(0 == 1, 1/0, 1)}
\end{document}

hmenke avatar Apr 14 '21 12:04 hmenke

It seems some laziness support is needed, either internal to ifthenelse and ?, or public as, for example \pgfmathdeclarelazy(function|operator).

muzimuzhi avatar Apr 15 '21 06:04 muzimuzhi

Also related questions in TeX.SX

ilayn avatar Apr 15 '21 07:04 ilayn

The culprit lies in the fact that the definition of \pgfmathifthenelse is

\pgfmathifthenelse:
macro:#1#2#3->\pgfmathparse {#1}\let \pgfmath@argument@1 =\pgfmathresult \pgfmathparse {#2}\let \pgfmath@argument@2 =\pgfmathresult \pgfmathparse {#3}\let \pgfmath@argument@3 =\pgfmathresult \pgfmathifthenelse@ {\pgfmath@argument@1 }{\pgfmath@argument@2 }{\pgfmath@argument@3 }

So we either need some separate implementations for all functions to handle laziness or we just redefine \pgfmathifthenelse after it has been defined using \pgfmathdeclarefunction. Are there any other functions that have to evaluate their arguments lazily?

hmenke avatar Apr 16 '21 18:04 hmenke

Are there any other functions that have to evaluate their arguments lazily?

and and or

\pgfmathprint{and(false, 1/0)}
\pgfmathprint{or(true, 1/0)}

muzimuzhi avatar Apr 17 '21 07:04 muzimuzhi