3
$\begingroup$

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?

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

1 Answer 1

4
$\begingroup$

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
$\endgroup$
11
  • 2
    $\begingroup$ Or make the index a pattern: Sum[x[k], {k, 1, n}] /. Sum[a_, {k_, 1, n}] :> a*xbar $\endgroup$
    – Bob Hanlon
    Feb 17 at 14:59
  • $\begingroup$ @bob Interesting, I didn't know summing will stop evaluation in this case. (Even Sum[a_, {h : k, 1, n}] evaluates to n a_! ) $\endgroup$
    – xzczd
    Feb 17 at 15:08
  • $\begingroup$ 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. $\endgroup$
    – Bob Hanlon
    Feb 17 at 15:14
  • $\begingroup$ Thanks. I've learned Attrbute of Hold*, useful Trace. $\endgroup$
    – jerry
    Feb 17 at 15:15
  • $\begingroup$ @BobHanlon I wonder how you find it, accidentally. $\endgroup$
    – jerry
    Feb 17 at 15:17

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.