# The definition of an Expectation operator

In trying to answer to the question Symbolic Expectation Value Evaluation, I have written the following piece of code

 m /: m[x_] = If[Attributes[x] ==  Constant, x, m[x]];
m /: m[x_ + y_] = m[x] + m[y];
m /: m[x_  y_] =
Which[Attributes[x][] == Constant, x  m[y],
Attributes[y][] == Constant, y m[x],
Attributes[x][] == Constant || Attributes[y][] == Constant,
x y, Attributes[x][] ! == Constant ||
Attributes[y][] ! == Constant, m[ x y]];


to begin with.

Then I have tried this

 SetAttributes[{α, β}, Constant]
m[α x + β]


which returns

 If[{} == Constant, x α, m[x α]] + If[{} == Constant, β, m[β]]


I do not know where is the problem perhaps the head of m[α x + β] which is Plus ????

• Try ===, does that work better? – Marius Ladegård Meyer Oct 24 '16 at 8:18
• Unfortunately not an !=== seems not to be defined – cyrille.piatecki Oct 24 '16 at 8:21
• You need =!= then – Marius Ladegård Meyer Oct 24 '16 at 8:21
• Like this m /: m[x_] = If[Attributes[x] == Constant, x, m[x]]; m /: m[x_ + y_] = m[x] + m[y]; m /: m[x_ y_] = Which[Attributes[x] == {Constant}, x m[y], Attributes[y] === {Constant}, y m[x], Attributes[x] =!= {Constant} || Attributes[y] =!= {Constant}, x y, (Attributes[ x] =!= {Constant}) || [Not] (Attributes[y] =!= {Constant}), m[x y]]; SetAttributes[{[Alpha], [Beta]}, Constant] m[[Alpha] x + [Beta]] it does not work neither – cyrille.piatecki Oct 24 '16 at 8:34
• You still have == in the first def of m[x_]... The thing is, when you use ==, stuff like {} == Constant is not False, it just does not evaluate, as you have seen from your output. With === it's either True or False. – Marius Ladegård Meyer Oct 24 '16 at 9:16

You could try something like the following:

ClearAll[m]
m[x_] := If[MemberQ[Attributes[x], Constant], x, Defer@m[x]]
m[x_ + y_] := m[x] + m[y]
m[x_ y_] := Which[
MemberQ[Attributes[x], Constant], x m[y],
MemberQ[Attributes[y], Constant], y m[x],
MemberQ[Attributes[x], Constant] || MemberQ[Attributes[y], Constant], x y,
FreeQ[Attributes[x], Constant] || FreeQ[Attributes[y], Constant], m[x y]
]


You then get:

SetAttributes[{a, b}, Constant]
m[a x + b]

(* Out: b + a m[x] *)