# Running a piece of a function only one time

I am trying to write a function which first analyzes and simplifies some large expressions and later uses some trial values for some other operations. The simplifications take a lot of time. So, I want to write in such a way that the first part of the function (which does the simplifications and so on) will be computed only at the first run of the function and for the later successive runs, only second part of the function will be computed.

For example take a big expression expr and my function looks

Test[expr_, coefficients_] :=(
(* First part (need to be calculated once) *)
newexpr = Simplify[expr];

(* Second part (can be evaluated multiple times depending on
different coefficients provided) *)
output = newexpr /. coefficients;
)


How can I do this in Mathematica?

Use memoization.

simplifyExpr[expr_] := simplifyExpr[expr] = Simplify[expr];

test[expr_, coefficients_] := Module[{newexpr},
newexpr = simplifyExpr[expr];
newexpr /. coefficients
]


I'm not 100% sure if this is what you're after, but you can try something along these lines:

TestA[expr_] := TestA[expr] = TestB[Simplify[expr]];
TestB[expr_][coefficients_] := expr /. coefficients;

(* To use, you only need to reference TestA *)
TestA[2 x + y][{x -> A, y -> B}]