I have an expression which I'd like to evaluate and use as a subexpression of a delayed-assigned expression. But I need it to be evaluated before actual assignment, while other parts of the full expression shouldn't be evaluated at this stage. See this simple example.:
testFunc[f_] := Evaluate[(5 + x - x)] D[f, x]
If I enclose the whole RHS into Evaluate, the expression does pre-evaluate, but since f doesn't explicitly depend on x, the whole expression becomes 0. OTOH, if done verbatim as above, Evaluate has no effect, and ?testFunc tells me that the RHS wasn't evaluated before assignment.
I've tried some other approaches, like this:
testFunc = Evaluate[(5 + x - x)] D[#, x] &
or this (hoping that the replacement will actually evaluate its RHS):
testFunc = mark[(5 + x - x)] D[#, x] & /. mark[x_] :> Evaluate[x]
But these approaches also don't appear to work.
Of course, one way is like
With[{expr = 5 + x - x}, testFunc = expr D[#, x] &]
, but when there are multiple such expr things, this way becomes very hard to follow, especially if it was created from a formula which I just wanted to optimize by pre-evaluation or simplification.
So, what is a good way to achieve pre-evaluation of subexpressions in delayed assignments or lambdas?
RuleConditionactually do? Does it evaluate the match before it's applied as a replacement? – Ruslan Feb 25 '17 at 06:20