2
$\begingroup$

This question already has an answer here:

I want to return a Hold expression but with some parts pre-evaluated. The easiest way to explain this is probably through code example. Here is what I have currently:

In[1]  := y = 3;

In[2]  := Hold[f[x, y]]
Out[2] := Hold[f[x, y]]

In[3]  := Hold[f[x, Evaluate[y]]]
Out[3] := Hold[f[x, Evaluate[y]]]

But I want something which returns Hold[f[x, 3]]. (My actual use case is to return a Hold expression involving the value of symbols which are local to a Block.)

How can I achieve this?

$\endgroup$

marked as duplicate by Szabolcs, Simon Woods, bbgodfrey, Leonid Shifrin, m_goldberg Feb 18 '15 at 0:25

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    $\begingroup$ Actually it might not be a duplicate, depending on what is your starting expression. You might do With[{y=1+1}, Hold[{x,y}]], which will first evaluate 1+1 then inject the result in a held expression. $\endgroup$ – Szabolcs Feb 17 '15 at 18:30
  • 1
    $\begingroup$ Recommendation: Hold[f[x, y]] /. HoldPattern[y] :> RuleCondition[y] -- and I think this should be closed as a duplicate of the question linked above. $\endgroup$ – Mr.Wizard Feb 17 '15 at 19:01
  • 1
    $\begingroup$ If the items to replace are always complete Symbols you could use With as Szabolcs showed, or: Function[y, Hold[f[x, y]]][y] $\endgroup$ – Mr.Wizard Feb 17 '15 at 19:03
  • $\begingroup$ I came up with Function[y, Hold[f[x, y]]][y] pretty much immediately after I posted the question. But anyway I think Szabolc's With solution is slightly cleaner. Yes, the thing to replace is always a Symbol, so it's not an exact duplicate of pattern replacement problem. $\endgroup$ – Saran Feb 17 '15 at 19:41
  • 1
    $\begingroup$ Since the thing to replace is always a Symbol I propose "reverse" replacement like this: y /. y_ :> Hold[f[x, y]] see: (1929) for examples. Would you object to having this question closed as "already answered" via a combination of (29317) and that? $\endgroup$ – Mr.Wizard Feb 17 '15 at 19:48
3
$\begingroup$

In version 10 have you looked at Inactivate and Activate?

(* ClearAll["Global`*"] *)
f[x_, y_] := x + y
expr = Inactivate[f[x, y]];

Now have a look at expr and see that f is inactivated. You can also activate f to see the result of the operation.

expr
Activate[expr]

Now set y and look at expr, then activate it.

y = 3;
expr
Activate[expr]

I hope this has helped.

$\endgroup$

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