Mathematica Programming » Assorted Tricks

Trott-Strzebonski (replace with evaluation)

This is the pattern we saw earlier for replacing a part of an expression with an evaluated expression:

 Hold[holdReplace]/.{holdReplace:>With[{eval=Integrate[Sin[θ], {θ, 2, π}]}, eval/;True]}

It is a nice trick to keep in mind for those cases when you need to insert something into a held context and it would be too much of a pain to wrap everything in a With .

This pattern is really a side-effect of the way scoping constructs work in Mathematica. By placing a Condition (/;) at the end of a scoping construct the whole construct evaluates or not depending on that condition.

We take advantage of the fact that the scoping construct will always scan to the end if there is a condition there, plus the fact that With inserts values, not symbols, to force the evaluated chunk of code to be inserted in our otherwise unevaluated structure.

See Also: