1
$\begingroup$

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.

$\endgroup$
1
  • $\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$ Commented Oct 10, 2018 at 10:55

1 Answer 1

1
$\begingroup$

(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]

14

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

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.