# Correct interpretation of /. (ReplaceAll)

Consider that you have a complicated expression, which is expensive in terms of running time and memory, and depends on some (initial) parameters. You want to test it for some simple values of the parameters, which simplifies a lot the evaluation.

For the sake of comprehension, suppose that the expression is

Table[k^2, {k, n}]


which depends on the parameter n.

If you test the expression with

Table[k^2,{k,n}] /. {n -> 5}


you obtain

Table::iterb: Iterator {k,n} does not have appropriate bounds. >>
{1, 4, 9, 16, 25}


so it seems to me that MMA in some sense pre-evaluate Table[k^2, {k, n}] , then substitute n with 5 and then evaluate Table[k^2, {k, 5}]. This is in partial contradiction with my understanding of the rule /.. I always though that MMA would evaluate Table[k^2, {k, n}] given that (or equivalently, assuming that) n is equal to 5 (and without making the "global" assignment n=5). That is, I though MMA implicitly does something like

f[n_]:=Table[k^2, {k, n}];
f


but in this case, there are no errors.

So, what does MMA do? What is the correct intepretation of /.?

Note that in my original expression, I got only the error (I exceeded the recursion limit), and not the evaluation with the substitution.

• ReplaceAll (/.) does not have the attribute HoldAll (or HoldFirst), so both arguments will be evaluated before the replacement is done. – Michael E2 Feb 5 '15 at 1:43
• Trace[Table[k^2, {k, n}] /. {n -> 5}] confirms what @MichaelE2 and @Nicola say. – Manuel --Moe-- G Feb 5 '15 at 1:50
• Thanks. Is there a quick way to evaluate Table[k^2, {k, n}] with n equal to 5 without making the assignment n=5 or writing explicitly Table[k^2, {k, 5}]? Imagine the parameter n is repeated several times in the expression so that I don't want to change them all, and that I do not want to define a dummy function f[n_] . – Nicola Feb 5 '15 at 2:06
• Block[{n = 5}, Table[..]]. Or Hold[Table[..]] /. n->5 // ReleaseHold; or a similar thing with Inactivate and Active (V10+ only). Possibly Quiet@Table[..] /. {n -> 5}, although it will be evaluated. – Michael E2 Feb 5 '15 at 2:25
• With is the function normally used to inject values into held expressions: With[{n = 5}, Table[k^2, {k, n}]] – Mike Honeychurch Feb 5 '15 at 5:10

ReplaceAll follows The Standard Evaluation Procedure. Some function have Attributes that make them follow a Non-Standard Evaluation procedure.