1
$\begingroup$

I am trying to do a seemingly simple thing:

f[x_, y_] := x + 3 y /. {x -> -x y}

the output for $x=1$ and $y=2$ is 7, so it doesn't make a substitution. How can I make this work without manually substituting the variables?

$\endgroup$
0

1 Answer 1

4
$\begingroup$

You want to use Set rather than SetDelayed

Clear[f]

f[x_, y_] := x + 3 y /. {x -> -x y}

DownValues[f]

(*  {HoldPattern[f[x_, y_]] :> (x + 3 y /. {x -> -x y})}  *)

Trace will show you the evaluation sequence

f[1, 2] // Trace

enter image description here

Clear[f]

f[x_, y_] = x + 3 y /. {x -> -x y}

(*  3 y - x y  *)

DownValues[f]

(*  {HoldPattern[f[x_, y_]] :> 3 y - x y}  *)

f[1, 2] // Trace

enter image description here

Beware that if x or y are defined before the Set this will fail. For a solution see:

$\endgroup$
2
  • $\begingroup$ I added a caveat and link to your answer (as well as my vote). I hope you do not mind. $\endgroup$
    – Mr.Wizard
    Dec 23, 2016 at 19:18
  • $\begingroup$ @Mr.Wizard - Thanks. $\endgroup$
    – Bob Hanlon
    Dec 23, 2016 at 19:21

Your Answer

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

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