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[5]
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 attributeHoldAll
(orHoldFirst
), so both arguments will be evaluated before the replacement is done. $\endgroup$Trace[Table[k^2, {k, n}] /. {n -> 5}]
confirms what @MichaelE2 and @Nicola say. $\endgroup$Table[k^2, {k, n}]
withn
equal to 5 without making the assignmentn=5
or writing explicitlyTable[k^2, {k, 5}]
? Imagine the parametern
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 functionf[n_]
. $\endgroup$Block[{n = 5}, Table[..]]
. OrHold[Table[..]] /. n->5 // ReleaseHold
; or a similar thing withInactivate
andActive
(V10+ only). PossiblyQuiet@Table[..] /. {n -> 5}
, although it will be evaluated. $\endgroup$With
is the function normally used to inject values into held expressions:With[{n = 5}, Table[k^2, {k, n}]]
$\endgroup$