4

I'm struggling with a command that doesn't do what I expect. This is my code

\newcommand{\expectation}[2][]{\mathrm{E}_{#1}\left[#2\right]}

\begin{document}
I get $\expectation{A}{B}$, but I expect $\mathrm{E}_{A}\left[B\right]$\\
Optional arguments, I get $\expectation{B}$, and I expect $\mathrm{E}\left[B\right]$
\end{document}

and this is the output enter image description here

This does not make a lot of sense to me. If I skip the newcommand and directly plug in what I want, everything looks fine. But the newcommand version with both inputs does something different. What am I missing?

(Even worse: I'm sure everything worked as intended yesterday. Today it doesn't anymore)

Edit: turns out this was due to a fixed bug in Texstudio. Optional arguments have to be called with brackets

6
  • 8
    Invoke it as \expectation[A]{B} with square, not curly brackets around the A. It is an optional argument. Curly braces are for mandatory arguments. Commented Aug 11, 2015 at 19:17
  • 1
    Also it might be an idea to use \ifblank from etoolbox to test if the _{#1} is even needed.
    – daleif
    Commented Aug 11, 2015 at 19:25
  • Thanks, now I understand. My editor (TeXstudio) suggests to use curly brackets for both arguments
    – Aaron
    Commented Aug 11, 2015 at 19:32
  • 1
    As it turns out, this is a known bug. Will be fixed in the next release
    – Aaron
    Commented Aug 11, 2015 at 19:38
  • 1
    You also might not want to have the left right construction as it easily becomes too excessive.
    – daleif
    Commented Aug 11, 2015 at 22:25

1 Answer 1

2

I would use the xparse package as it keeps the default behaviors for an optional argument very manageable.

\documentclass[10pt]{article}

\usepackage{xparse}

%\ExplSyntaxOn
    \DeclareDocumentCommand{\expectation}{ O{} m }{%
        $\mathrm{E}_{#1}\left[#2\right]$%
    }
%\ExplSyntaxOff

% choose a different way of producing subscripts if you need ExplSyntax

\begin{document}
    I get \expectation[A]{B}, but I expect $\mathrm{E}_{A}\left[B\right]$\\
    Optional arguments, I get \expectation{B}, and I expect $\mathrm{E}\left[B\right]$
\end{document}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .