I have a very large function f[x_,y_,z_] and it's too cumbersome to type it directly. So I wish to break the definition and use (/.) multiple times, as follows (indicatively):

f[x_, y_,z_] := (int1 + int2 + int3)/.rule1/.rule2;
rule1 = {int1 -> iint1, int2 -> iint2, int3 -> iint3};
rule2 = {iint1 -> 1*x, iint2 -> 2*y, iint3 -> 3*z};

But this does not work. When I try to evaluate f[1,2,3], it does not perform the transformation rule2 and gives me f[1,2,3]=x + 2y + 3z instead of the evaluated number value 1*1 + 2*2 + 3*3 = 14.

I think this is because rule2's definition on line 3 does not come into the scope of my function declaration on line 1, so the x I write in rule2 is not the same x_ I'm trying to relate to.

How do I solve this? Thank you.

  • $\begingroup$ This is a good reason to use a scoping construct like Block[] or Module[]. You can then do something like f[x_, y_, z_] := Module[{int1, int2, int3, rule1, rule2}, int1 = (* stuff *); (*stuff *) (int1 + int2 + int3) /. rule1 /. rule2] $\endgroup$ – J. M. is in limbo Oct 10 '18 at 10:55

(1) define rule1 and rule2 before f, and (2) wrap the rhs of the definition with Evaluate to suppress the HoldAll attribute of SetDelayed:

f[x_, y_, z_] := Evaluate[(int1 + int2 + int3) /. rule1 /. rule2];
f[1, 2, 3]


  • $\begingroup$ Works perfect! Thanks. $\endgroup$ – QMrules Oct 10 '18 at 11:09
  • $\begingroup$ @QMrules, my pleasure. Welcome to mma.se. $\endgroup$ – kglr Oct 10 '18 at 11:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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