TeX - LaTeX Asked on March 2, 2021
I want to define a new command such that when a first and only argument is given it does one thing and when a second argument is given it expands the first argument. The idea is to replicate the probability function. One argument is for probability distribution and two arguments are for conditional probability distribution. I really don’t know how to do it.
The (completed) following code
documentclass{article}
usepackage[utf8]{inputenc}
usepackage{amssymb}
newcommand{PP}[2]{???}
begin{document}
$PP{X}$
$PP{X}{Y}$
end{document}
should print
mathbb{P}{left({X}right)}
mathbb{P}{left({X}middle|{Y}right)}
I wouldn’t like to have an optional argument because it would affect the order and readability of the code. I mean, I prefer PP{X}{Y} over PP[Y][X].
Could you please help me?
Thanks
You can do better, with a much easier user syntax.
documentclass{article}
usepackage{amsmath,amssymb}
usepackage{xparse}
ExplSyntaxOn
NewDocumentCommand{PP}{ s O{} >{SplitArgument{1}{|}}m }
{
mathbb{P}
IfBooleanTF{#1}
{ PPauto #3 }
{ PPfixed {#2} #3 }
}
NewDocumentCommand{PPauto}{mm}
{
left(
IfNoValueTF{#2} { #1 } { #1 ;middle|; #2 }
right)
}
NewDocumentCommand{PPfixed}{mmm}
{
mathopen{#1(}
IfNoValueTF{#3} { #2 } { #2 mathrel{#1|} #3 }
mathclose{#1)}
}
ExplSyntaxOff
begin{document}
[
PP{X} quad PP[big]{X} quad PP*{frac{X}{2}}
]
[
PP{X|Y} quad PP[big]{X | Y} quad PP*{frac{X}{2} | Y}
]
end{document}
The command PP
has an optional argument for the size (never rely on left
and right
alone) or a *
variant for the automatic sizing (use it only if really necessary).
The mandatory argument is split at |
, if present. So the input code is much easier to read. Spaces around |
are irrelevant.
Correct answer by egreg on March 2, 2021
I propose a syntax that uses a single argument only. EDITED to include Mico's spacing suggestion.
documentclass{article}
usepackage{listofitems,amssymb}
newcommandPP[1]{%
readlistarglist{#1}
ifnum1=arglistlenrelax
mathbb{P}{left(#1right)}
else
mathbb{P}{left(arglist[1];middle|;arglist[2]right)}
fi
}
begin{document}
$PP{X}$
$PP{X,Y}$
end{document}
Answered by Steven B. Segletes on March 2, 2021
Inspired of Werner's Answer and similar to Segletes's answer above:
documentclass{article}
usepackage{amssymb}
newcommand{pp}[1]{ppaux#1relax}
defppaux#1#2relax{%
ifnumpdfstrcmp{#2}{}=0
mathbb{P}{left(#1right)}
else
mathbb{P}{left(#1 ;middle|; #2right)}
fi
}
begin{document}
$pp{X}$
$pp{XY}$
$pp{{XY}}$
end{document}
Answered by user108724 on March 2, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP