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?
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
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
Beware that if x
or y
are defined before the Set
this will fail. For a solution see: