3
$\begingroup$

I would like to do something like

f[x_]:=g[x];

But I don't want that definition of f to change if the definition of g changes later.

How can I proceed?

$\endgroup$
5
  • 4
    $\begingroup$ f[x_] =g[x] ? $\endgroup$
    – LLlAMnYP
    Commented Jul 13, 2017 at 14:50
  • $\begingroup$ oooh well. Sorry for my question it seems that I still don't know some basics of language :D. I thought we could only create functions with the := symbol $\endgroup$
    – StarBucK
    Commented Jul 13, 2017 at 14:52
  • 2
    $\begingroup$ @LLlAMnYP If g[x_?NumericQ] = x then f will change if g changes $\endgroup$
    – Coolwater
    Commented Jul 13, 2017 at 14:52
  • $\begingroup$ Not so basic, especially if x is allready defined and you don't want to use the definition of x. I think this latest problem has been treated in a post. $\endgroup$
    – andre314
    Commented Jul 13, 2017 at 16:42
  • 1
    $\begingroup$ I can't find the post I mentioned just above. Among the possibilities one can 1) of course, change de variable name 2) use a formal parameter 3) use Block[{x},f[x_]:=g[x]], though I don't know if 3) is a good practise. $\endgroup$
    – andre314
    Commented Jul 13, 2017 at 16:53

2 Answers 2

3
$\begingroup$

If g[x] evaluates to what you need, you can define f with either = or :=:

f[x_] = g[x];
(f[x_] := #) &[g[x]]

If a single evaluation of g doesn't return all that matters, assign it to another symbol whose definitions are to be kept fixed:

  UpValues[g2] = UpValues[g]   /. g -> g2;    DownValues[g2] = DownValues[g]   /. g -> g2;
Attributes[g2] = Attributes[g] /. g -> g2;       Options[g2] = Options[g]      /. g -> g2;
 SubValues[g2] = SubValues[g]  /. g -> g2;  FormatValues[g2] = FormatValues[g] /. g -> g2;

and replace g by g2 in your definition for f

$\endgroup$
2
$\begingroup$

Here's a simple idea of how you can explore the use of functions:

g[x_?NumericQ] := x
f[x_] := g[x]

Testing:

f[x]

g(x)

f[2]

2

g[x]

g(x)

g[2]

2

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.