3

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?

QuantumDot
  • 19,601
  • 7
  • 45
  • 121

1 Answers1

4

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*)]

enter image description here

...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.

Mike Honeychurch
  • 37,541
  • 3
  • 85
  • 158