# ReplaceAll inside an Iterator

I'd like to apply a set of rules to an expression defining the iterators of the table, like this:

ExampleParameters = {x0 -> 0, xp -> 1}
Table[x,{x, x0 - 3*xp, x0 + 3*xp, xp} /. ExampleParameters]


The kernel returns the following error:

Table::itform: Argument {x, x0 - 3 xp, x0 + 3 xp, xp} /. ExampleParameters
at position 2 does not have the correct form for an iterator.


Any ideas on how to generalize the table expression? Explicitly using

Table[x,ReplaceAll{x, x0-3*xp, x0+3*xp, xp}, ExampleParameters]]


Mathematica throws the error because Table has the HoldAll attribute which prevents the replacement from being performed before Table sees the iterator. You can force evaluation using Evaluate:

Table[x, Evaluate[{x, x0 - 3*xp, x0 + 3*xp, xp} /. exampleParams]]


Alternatively, instead of ReplaceAll, use With:

With[{x0 = 0, xp = 1}, Table[x, {x, x0 - 3*xp, x0 + 3*xp, xp}]]


In similar situations I like to use a custom-defined With-like function that can take parameter lists. I described this function here and I'm going to reproduce it in this answer as well for completeness:

ClearAll[withRules]
SetAttributes[withRules, HoldAll]
withRules[rules_, expr_] :=
First@PreemptProtect@InternalInheritedBlock[
{Rule, RuleDelayed},
SetAttributes[{Rule, RuleDelayed}, HoldFirst];
Hold[expr] /. rules
]

withRules[exampleParams, Table[x, {x, x0 - 3*xp, x0 + 3*xp, xp}]]

• Perfect, the Evaluate[] trick did the job - what would be the advantage of using WithRules instead?
– qdot
Apr 22, 2012 at 21:53
• @qdot What if you use those parameters in multiple places in the expression and can't place the Evaluate at the right position, or need to use a separate ReplaceAll for each? In this case With/withRules` is a lot more convenient. Apr 23, 2012 at 6:52