0
$\begingroup$

How should I use replace so that

f[x_] := x^2
Replace[f[3], 3 -> 1]

OUT = 9

evaluates to 1, instead of 9? This way, the replacement of the argument is done before the call to the function

$\endgroup$
4
  • 1
    $\begingroup$ Replace[Hold@f[3], 3 -> 1, Infinity] // ReleaseHold? $\endgroup$
    – kglr
    Commented May 26, 2016 at 16:51
  • 4
    $\begingroup$ ReplaceAll[Unevaluated[f[3]], 3 -> 1]? $\endgroup$
    – BlacKow
    Commented May 26, 2016 at 16:51
  • 2
    $\begingroup$ A slightly more complicated version of this question: (25652), and a related instance: (30193). Also see: (25476) $\endgroup$
    – Mr.Wizard
    Commented May 26, 2016 at 17:00
  • 2
    $\begingroup$ Possible duplicates: (3105), (91394) $\endgroup$
    – Mr.Wizard
    Commented May 26, 2016 at 17:09

1 Answer 1

1
$\begingroup$
Activate@Replace[Inactive[f][3],3->1, Infinity]

1

or

Replace[Hold@f[3], 3 -> 1, Infinity] // ReleaseHold

1

$\endgroup$
3
  • 1
    $\begingroup$ We have had this very question several times before. If you have time would you look for a duplicate? Edit: I found I couple of possible duplicates and linked them above. $\endgroup$
    – Mr.Wizard
    Commented May 26, 2016 at 16:59
  • 1
    $\begingroup$ @Mr.Wizard, could not find anything useful in the first 2-3 pages of search results with search terms Replace ,Unevaluated and Inactive. Btw, which search terms did you use to get the links you posted? $\endgroup$
    – kglr
    Commented May 26, 2016 at 17:32
  • 1
    $\begingroup$ Thank you for looking! I believe I was using the query code:"/." code:unevaluated is:answer but most of the time I feel like stumbling upon the right post is mostly blind luck; this is why I take so much time adding all the Related: links, because I often find things faster by following the network of connected posts. $\endgroup$
    – Mr.Wizard
    Commented May 26, 2016 at 18:12

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