7
$\begingroup$

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]] 

leads to the same error.

$\endgroup$

1 Answer 1

9
$\begingroup$

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@Internal`InheritedBlock[
    {Rule, RuleDelayed},
    SetAttributes[{Rule, RuleDelayed}, HoldFirst];
    Hold[expr] /. rules
]

withRules[exampleParams, Table[x, {x, x0 - 3*xp, x0 + 3*xp, xp}]]
$\endgroup$
2
  • $\begingroup$ Perfect, the Evaluate[] trick did the job - what would be the advantage of using WithRules instead? $\endgroup$
    – qdot
    Apr 22, 2012 at 21:53
  • $\begingroup$ @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. $\endgroup$
    – Szabolcs
    Apr 23, 2012 at 6:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.