1
$\begingroup$

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 ????

$\endgroup$
  • $\begingroup$ Try ===, does that work better? $\endgroup$ – Marius Ladegård Meyer Oct 24 '16 at 8:18
  • $\begingroup$ Unfortunately not an !=== seems not to be defined $\endgroup$ – cyrille.piatecki Oct 24 '16 at 8:21
  • 3
    $\begingroup$ You need =!= then $\endgroup$ – Marius Ladegård Meyer Oct 24 '16 at 8:21
  • $\begingroup$ 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 $\endgroup$ – cyrille.piatecki Oct 24 '16 at 8:34
  • 2
    $\begingroup$ 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. $\endgroup$ – Marius Ladegård Meyer Oct 24 '16 at 9:16
1
$\begingroup$

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] *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.