TransWikia.com

Defining function in terms of previously defined symbol

Mathematica Asked by GaloisFan on June 26, 2021

With a very high frequency I find myself working with giant and hard to alter expressions in a situation where it would be convenient to do something like

function = x^2;

f[x_]:= function;

which obviously doesn’t work. I have also tried using InputForm[function] which does not work either.

How can I do something like this?

2 Answers

ClearAll[f,x]
function = x^2;
f[x_] = function;
DownValues[f]  (* {HoldPattern[f[x_]] :> x^2} *)


ClearAll[f]
f[x_] := x^2;
DownValues[f]  (* {HoldPattern[f[x_]] :> x^2} *)

Correct answer by Alan on June 26, 2021

The problem you encountered is due to the evaluation algorithm used by Mathematica. In the documentation of SetDelayed is this statement

SetDelayed has attribute HoldAll, rather than HoldFirst.

What this means is that you do want the RHS to be evaluated in your case. As usual, you can force this by using f[x_]:=Evaluate[function] or else by using the alternate Set function with f[x_]=function. In the usual situation such as f[x_]:=x^2 we do want to RHS to be held unevaluated until the function is called. In your case function is a symbol which, only when evaluated, becomes the x^2 that you want in the function definition.

The decision to use = instead of := is a matter of preference and convenience but it is context dependent. For example, in the case of function=x^2 you have to ensure that the symbol, in this case x, does not have a value, otherwise function will use that value which is not what you want. You have to remember to use ClearAll[x] or x=. before using x to remove any value that x has. If you use the standard f[x_]:=x^2 then this is automatically taken care of. You will run into the same problem if you use f[x_]=x^2 and forget to use := instead because if x has a value then that value will be used in the function definition and that is almost certainly not what you want.

Answered by Somos on June 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP