# Problem with immediate function definition

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?

You can make use of LanguageExtendedDefinition 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 = "one";
g[n_Integer] = "integer";
g[n_Real] = "real";
g[n_Rational] = "rational";


Using LanguageExtendedDefinition to burn this definition of g into the definition of f:

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


Now, clear g:

Clear[g]


Check whether f still behaves as expected:

f
f
f[3/2]
f[1.5]
f


"one"

"integer"

"rational"

"real"

0

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

With[{g = Function[x, 4]},
f = Function[x, If[x < 3, g[x], 0]]
]