1
$\begingroup$

I have a problem with the definition of a function that uses another function whose value is to be changed later.

For example:

g[x_] := 4
f[x_] = If[x < 3, g[x], 0]

If I then change the value of g , then f also varies; on the other hand, if I don't use the If function and define, for example:

f[x_] = g[x]

then f remains fixed, as I wanted.

How do I fix this?

$\endgroup$
1
$\begingroup$

You can make use of Language`ExtendedDefinition which is used to move code from a desktop to the cloud, so should be robust (in this example, it is also possible to use DownValues in a similar fashion). Basically, get the extended definition of your function g at the time of interest, and then use that function in the definition of the function f. Here is an example of a function g:

g[1] = "one";
g[n_Integer] = "integer";
g[n_Real] = "real";
g[n_Rational] = "rational";

Using Language`ExtendedDefinition to burn this definition of g into the definition of f:

With[{def = Language`ExtendedDefinition["g"]},
    f[x_] := Block[{g},
        Language`ExtendedDefinition["g"] = def;
        If[x<3, g[x], 0]
    ]
]

Now, clear g:

Clear[g]

Check whether f still behaves as expected:

f[1]
f[2]
f[3/2]
f[1.5]
f[10]

"one"

"integer"

"rational"

"real"

0

$\endgroup$
0
$\begingroup$

It looks like the value for f remains unevaluated until the If's condition can be verified as True or False. As such, g[x] is re-evaluated every time the condition can be checked.

To avoid this, use memoization:

f[x_] := f[x] = If[x < 3, g[x], 0];

This makes f save its value at each x every time it is evaluated.

Alternatively, if even memoization allows too many different function evaluations and you need to use the same g in every use of f, then embed g[x] in the definition by doing something like:

f[x_] := If[x < 3, Evaluate[g[x]], 0];
$\endgroup$
0
$\begingroup$
With[{g = Function[x, 4]},
 f = Function[x, If[x < 3, g[x], 0]]
 ]
$\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.