[Tex/LaTex] auto-detect conditional probabilities in macro

macrosmath-mode

Is it possible to write a macro that detects whether there is a | character in its arguments, and expands that to something else?

In concrete terms, I want to be able to use the following definitions simultaneously:

\def\P(#1){\Pr\left( #1 \right)}
\def\P(#1|#2){\Pr\left( #1 \mid #2 \right)}

Whenever in the text I write a probability $\P(X)$, the first definition should be used, whereas $\P(X|Y)$ should use the second.

If possible, a simple TeX/LaTeX solution is preferred, since many journals put restrictions on usable packages.

I know this could be achieved using simply two different macros. The reason for this question is that the abstract of a paper often ends up printed in plain text (think the arXiv email), and I would like it to be as readable as possible.

Best Answer

This can differentiate the argument as you requested.

\documentclass{article}
\def\P(#1){\Phelper#1|\relax\Pchoice(#1)}
\def\Phelper#1|#2\relax{\ifx\relax#2\relax\def\Pchoice{\Pone}\else\def\Pchoice{\Ptwo}\fi}
\def\Pone(#1){\Pr\left( #1 \right)}
\def\Ptwo(#1|#2){\Pr\left( #1 \mid #2 \right)}
\def\Pr{\mathbf{Pr}}
\begin{document}
$\P(A)$ or $\P(A|B)$
\end{document}

enter image description here

If your arguments are always short, then a simpler \def\P(#1){\Pr(#1)} may be sufficient for your need. But since you are using \left(...\right), it might be the case that you want to handle tall arguments. In that case, I would replace \mid with \,\middle|\, so that you could achieve the following, which works in both text style and display style:

\documentclass{article}
\def\P(#1){\Phelper#1|\relax\Pchoice(#1)}
\def\Phelper#1|#2\relax{\ifx\relax#2\relax\def\Pchoice{\Pone}\else\def\Pchoice{\Ptwo}\fi}
\def\Pone(#1){\Pr\left( #1 \right)}
\def\Ptwo(#1|#2){\Pr\left( #1 \,\middle|\, #2 \right)}
\def\Pr{\mathbf{Pr}}
\begin{document}
\centering$\P(A)$ or $\P(A|B)$

\[\P(\displaystyle\frac{x}{2}>1 | x>0) = 0.5\]
\end{document}

enter image description here

Related Question