# How to inject segments of code into functions defined by SetDelayed [duplicate]

I need to define a set of functions that are written in terms of common but lengthy expressions. To effect this, I want to inject abbreviations for such expressions into the RHS of SetDelayed of multiple functions. Something like this:

Clear[f, g];
Module[{abbrev = Sum[int[i], {i, 1, n}]},
f[n_] := abbrev + y;
g[n_] := abbrev^2;
(*and so on*)
]


But it doesn't work. First, the n_ in the LHS is failing to match the n in the RHS. Second, the kernel first evaluates the RHS of abbrev before injecting it into the RHSs of f and g. In my program, that consumes time that could otherwise be saved.

What can I do to solve these problems?

• With isn't working on my computer (Mathematica 10.2 on Mac OS X). What version are you using? Dec 21 '15 at 21:28
• @QuantumDot what are int and y terms in your code? Dec 21 '15 at 21:32
• int[i] is a recursively defined symbolic function (the result is usually a polynomial plus some logarithms), y is a similar object (polynomial+logs) but known explicitly (no recursive code). Dec 21 '15 at 21:35
• Ok, here is one way: (f[n_] := # + y; g[n_] := #^2;) &[ Sum[int[i], {i, 1, n}] ] there should be a duplicate somewhere.
– Kuba
Dec 21 '15 at 21:36
• Not the one I've thought about but I think it's good enough: 20766
– Kuba
Dec 21 '15 at 21:39

I'm not sure how robust this is. It is quick and dirty so to speak.

With[{abbrev := Sum[int[i], {i, 1, n\$}]},
f[n_] := abbrev + y;
g[n_] := abbrev^2
(*and so on*)] ...but I think @kuba's link provides better alternatives.

Edit

Such an alternative includes:

Clear[f, g];
Module[{abbrev := Sum[int[i], {i, 1, n}]},
SetDelayed @@ {f[n_], abbrev + y};
g[n_] := abbrev^2]


Where you do not have to modify the n with dollar signs. The explanation for why this works is given in the post by Mr Wizard and Leonid.