3

Here is an simple replacement:

 Log[x[k]] /. Log[a_] -> a*xbar

I get the answer in my mind:

xbar x[k]

Similarly, I use another replacement:

Sum[x[k],{k,1,n}]/.Sum[a_,{k,1,n}]->a*xbar

Should the answer be x[k]*xbar ? However, the replacement is disappointing:

enter image description here

I remain puzzled after much pondering. It seems the function Product at it also is deceptive.

What is the particularity of Sum/Product in replacement? Why is that?

xzczd
  • 65,995
  • 9
  • 163
  • 468
jerry
  • 31
  • 2

1 Answers1

4

If a function doesn't own Hold* attribute, it'll evaluate its arguments from left to right. ReplaceAll (/.) and Rule (/.) don't own Hold* attribute. In other words, Sum[a_, {k, 1, n}] evaluates before the replacement happens. There's no explicit k in a_, so Sum thinks it's a constant and evaluates to n a_. This can be checked with Trace:

Sum[x[k], {k, 1, n}] /. Sum[a_, {k, 1, n}] -> a xbar // Trace

enter image description here

Then how to fix? Just stop summing with HoldPattern:

Sum[x[k], {k, 1, n}] /. HoldPattern@Sum[a_, {k, 1, n}] -> a xbar

Alternatively:

Sum[x[k], {k, 1, n}] /. (h : Sum)[a_, {k, 1, n}] -> a xbar

Or:

Sum[x[k], {k, 1, n}] /. Verbatim[Sum][a_, {k, 1, n}] -> a xbar
xzczd
  • 65,995
  • 9
  • 163
  • 468