7

Is there an option to let me assign the old function of f to g, without changing g when reassigning f?

This piece of code describes my problem:

f[x_] := x^2

f[2] (Output: 4)

g = f

g[2] (Output: 4)

f[x_] := x^3

f[2] (Output: 8) g[2] (Output: 8)

Tobias
  • 563
  • 2
  • 7

2 Answers2

9

Clear your current g and f. Start from a fresh kernel and use

ResourceFunction["CopyDefinitions"][f, g];

See the notebook on the WFR if you want to see how this is achieved. (The CopySymbol defined there is basically taking Language`ExtendedDefinition[f] and replacing the symbol)

Remove["Global`*"]
f[x_] := x^2
f[2] (*Output:4*)
ResourceFunction["CopyDefinitions"][f, g];
g[2] (*Output:4*)
f[x_] := x^3
f[2] (*Output:8*)
g[2] (*Output:4*)
flinty
  • 25,147
  • 2
  • 20
  • 86
5

Mathematica is an expression rewriting system. Your problem is that

g=f

Means "whenever you see g, substitute f". So, g[2] gets rewritten as f[2] which then gets rewritten according to the definition of f.

Here, you may do

g[x_]=f[x]

This evaluates f[x] and uses that for your g definition. Redefining f then has no effect.

This will require more elaboration if evaluating f with a symbolic argument causes trouble.

John Doty
  • 13,712
  • 1
  • 22
  • 42