# Make Mathematica wait before replacing?

How can I force Mathematica to completely evaluate a subexpression before using a replacement rule?

For example, consider the following definition (for the series of n correction factors in Stirling's formula):

stirlingSeries[n_] :=
Series[Exp[
Total[Table[(-1)^(k - 1)/k t^k h^(k/2 - 1), {k, 3,
2 n + 2}]]], {h, 0, n}] /.
t^m_ -> If[Mod[m, 2] == 0, (m - 1)!!, 0]


What I want to tell Mathematica to do is replace powers of t at the end, as the very last step in calculating stirlingSeries[n]. Instead, it replaces them first. This changes the result of the calculation.

-
I don't think I see the problem. What are you expecting instead? –  Mr.Wizard Feb 1 '13 at 2:25

Let me guess what could be the problem: you could have defined m before executing the definition of stirlingSeries that you wrote in the question. In that case, the replacement rule -> would have assigned the current value of m, instead of the delayed value. To illustrate what I think went wrong, here is the scenario:

m = 4

(* ==> 4 *)

stirlingSeries[n_] :=
Series[Exp[
Total[Table[(-1)^(k - 1)/k t^k h^(k/2 - 1), {k, 3,
2 n + 2}]]], {h, 0, n}] /.
t^m_ -> If[Mod[m, 2] == 0, (m - 1)!!, 0]

stirlingSeries[4]


$$1+\sqrt{h}-\frac{7 h}{12}+\frac{199 h^{3/2}}{540}-\frac{3193 h^2}{12960}+\frac{46801 h^{5/2}}{272160}-\frac{6084467 h^3}{48988800}+\frac{13558333 h^{7/2}}{146966400}-\frac{494880067 h^4}{7054387200}+O\left(h^{9/2}\right)$$

stirlingSeries[n_] :=
Series[Exp[
Total[Table[(-1)^(k - 1)/k t^k h^(k/2 - 1), {k, 3,
2 n + 2}]]], {h, 0, n}] /.
t^m_ :> If[Mod[m, 2] == 0, (m - 1)!!, 0]

stirlingSeries[4]


$$1+\frac{h}{12}+\frac{h^2}{288}-\frac{139 h^3}{51840}-\frac{571 h^4}{2488320}+O\left(h^{9/2}\right)$$

On the last lines, I changed the definition to RuleDelayed (:>) which does what I believe you want: take the value of m to be that found in the pattern t^m_.

-