2
$\begingroup$

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

g=1+x^2 

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?

$\endgroup$
4
  • $\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, 2016 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, 2016 at 17:10
  • $\begingroup$ myfunc[f_] := Simplify[(f/g)] /. (g -> 1 + x^2) $\endgroup$ Apr 25, 2016 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, 2016 at 1:34

2 Answers 2

2
$\begingroup$

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:

Clear[myfunc]
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;

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

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

Maybe something like this?

g = 1 + x^2
Unprotect[saveg]
saveg = g;
myfunc[f_] := Simplify[(f/saveg)]
Protect[saveg]
$\endgroup$

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.