I would like to define a function like

myfunc[f_] := Simplify[(f/g)]

where g will be substituted/replaced with the current value of g at the time of definition. In practise, g will be complicated and myfunc will be defined over and over again. However, between these redefinitions I want it to be statically set. If


then I want the equivalent of typing

myfunc[f_] := Simplify[(f/(1+x^2))]

The following works but seems pretty arcane:

myfuncA[f_] := Evaluate[With[{yy = g}, Hold[Simplify[f/yy]]]]

myfunc[f_] := ReleaseHold[myfuncA[f]]

How to accomplish this simple task?

  • $\begingroup$ Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! $\endgroup$ – Michael E2 Apr 25 '16 at 17:10
  • 1
    $\begingroup$ You can format inline code and code blocks by selecting the code and clicking the {} button above the edit window. The edit window help button ? is also useful for learning how to format your questions and answers. You may also find this this meta Q&A helpful $\endgroup$ – Michael E2 Apr 25 '16 at 17:10
  • $\begingroup$ myfunc[f_] := Simplify[(f/g)] /. (g -> 1 + x^2) $\endgroup$ – Peter Roberge Apr 25 '16 at 17:43
  • $\begingroup$ If the substitution for g were to be made for one particular instance and the value substituted was simple then this construction would work. In my example, the 1+x^2 is a placeholder for a complicated expression calculated elsewhere over and over again. So this particular method doesn't provide the flexibility I need. $\endgroup$ – user39757 Apr 26 '16 at 1:34

I think that value injection using With will work for you.

Let's first define the sample g value you want:

g = 1 + x^2

Now we define myfunc injecting the current definition of g inside its definition:

With[{g = g}, myfunc[f_] := Simplify[f/g]]

Now let's change the value of g and check whether the definition of myfunc is affected:

g = 3;

(* Out: expr/(1+x^2) *)

myfunc[1 + x^2 - x^3 - x^5]
(* Out: 1 - x^3 *)
  • $\begingroup$ This works and is the prototypical construction needed! $\endgroup$ – user39757 Apr 26 '16 at 12:30

Maybe something like this?

g = 1 + x^2
saveg = g;
myfunc[f_] := Simplify[(f/saveg)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.