1

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][[1]] == Constant, x  m[y],  
  Attributes[y][[1]] == Constant, y m[x], 
  Attributes[x][[1]] == Constant || Attributes[y][[1]] == Constant, 
  x y, Attributes[x][[1]] ! == Constant || 
  Attributes[y][[1]] ! == 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 ????

cyrille.piatecki
  • 4,582
  • 13
  • 26
  • Try ===, does that work better? – Marius Ladegård Meyer Oct 24 '16 at 08:18
  • Unfortunately not an !=== seems not to be defined – cyrille.piatecki Oct 24 '16 at 08:21
  • 3
  • 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 08:34
  • 2
    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 09:16
  • Sorry Marius, it's holidays and I was obliged to come back home to feed my childs. Now 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], make a long recursion. Attributes[y] === {Constant}, y m[x], Attributes[x] =!= {Constant} || Attributes[y] =!= {Constant}, x y, [Not] (Attributes[x] =!= {Constant}) || [Not] (Attributes[ y] =!= {Constant}), m[x y]]; SetAttributes[{[Alpha], [Beta]}, Constant] m[[Alpha] x + [Beta]] – cyrille.piatecki Oct 24 '16 at 12:33

1 Answers1

1

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] *)
MarcoB
  • 67,153
  • 18
  • 91
  • 189