Is there any particularity of Sum/Product in replacement

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:

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?

• What do you expect after applying the rule? Sum[x[k] xbar,{k,1,n}]? Feb 17 at 14:39

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


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

• Or make the index a pattern: Sum[x[k], {k, 1, n}] /. Sum[a_, {k_, 1, n}] :> a*xbar Feb 17 at 14:59
• @bob Interesting, I didn't know summing will stop evaluation in this case. (Even Sum[a_, {h : k, 1, n}] evaluates to n a_! ) Feb 17 at 15:08
• I am only guessing but I suspect that in the process of localizing the index variable, internally k doesn't look like k. Using a pattern would cause a match to whatever its representation. Feb 17 at 15:14
• Thanks. I've learned Attrbute of Hold*, useful Trace. Feb 17 at 15:15
• @BobHanlon I wonder how you find it, accidentally. Feb 17 at 15:17