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?


2 Answers 2


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

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.