3
$\begingroup$

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?

$\endgroup$
  • $\begingroup$ 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... $\endgroup$ – Albert Retey Apr 24 '14 at 13:53
7
$\begingroup$

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}
$\endgroup$
  • $\begingroup$ Nice first answer. +1 $\endgroup$ – ciao Apr 24 '14 at 0:12
3
$\begingroup$

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 :=)

$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – Chris Degnen Feb 16 '18 at 11:08

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.