3

I need to change a function symbol multiple times by assigning another symbol to it, but when I'm trying to do that the symbols overwrite each other.

I'm assuming this is because the assignment is by reference.

For example, this input:

func1[x_] := x^2
func2 = func1; func3[x_] := func1[x]
{func1, func2, func3}
{func1[#], func2[#], func3[#]} &[4]
func1[x_] := -x
{func1[#], func2[#], func3[#]} &[4]

Gives the following output:

Out[]= {func1, func1, func3}
Out[]= {16, 16, 16}
Out[]= {-4, -4, -4}

How could I make the assignment so changing one function doesn't influence changing the other?

User
  • 295
  • 1
  • 6
  • it might well not be the right choice for your problem, but I think you should be aware that for those cases where you treat a function as an object, using Functions is often more appropriate than downvalue-definitions. When using func1=Function[x,x^2] for the first definition and func1=Function[x,-x] for the second your example will work as you want... – Albert Retey Apr 24 '14 at 13:53

2 Answers2

8

You should use DownValues (see second Application), with a transformation rule.

Using your code, this input:

In[345]:= func1[x_] := x^2
DownValues[func2] = DownValues[func1] /. func1 -> func2;
func3[x_] := func1[x]
{func1, func2, func3}
{func1[#], func2[#], func3[#]} &[4]
func1[x_] := -x
{func1[#], func2[#], func3[#]} &[4]

Gives the following output:

Out[348]= {func1, func2, func3}
Out[349]= {16, 16, 16}
Out[351]= {-4, 16, -4}
Dvir Berebi
  • 196
  • 3
3

The simple way to do it is

func2[x_] = func1[x];

then

func1[x_] := x^2
func2[x_] = func1[x];
{func1, func2}
{func1[#], func2[#]} &[4]
func1[x_] := -x
{func1[#], func2[#]} &[4]

gives

{func1, func2}
{16, 16}
{-4, 16}

Here are links to two valuable answers highly relevant to your problem, Understand what Set (=) really does and Understand the difference between Set (or =) and SetDelayed (or :=)

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
  • If you have also func1[4] := False this is not copied to func2, and if you have only func1[4] := False then func2 refers to func1, so if func1 is cleared func2 does nothing. – Chris Degnen Feb 16 '18 at 11:08