Re: Best practice passing expressions to functions
- To: mathgroup at smc.vnet.net
- Subject: [mg85315] Re: Best practice passing expressions to functions
- From: Szabolcs Horvát <szhorvat at gmail.com>
- Date: Tue, 5 Feb 2008 19:46:46 -0500 (EST)
- References: <fo9gvu$t1l$1@smc.vnet.net>
Remo Aschwanden wrote: > Hi > > I want to write procedures that accept expressions as parameters and be= > able define functions based on these expressions, i.e. > > f[exp_]:=Module[ > "g[x_] := exp " > ] > > The code between the " " should clarify what I intend to do. Calling > f[x^2-2x+4] > should lead to the definition of a function (or pattern) > g[x_]:=x^2-2x+4; > > What's the best way to do this? How can I do this without being > dependent on the variables used in the expressions ("x")? I am not sure I understand completely what you would like to do. Do you mean something like this? define[fun_Symbol,var_Symbol,exp_]:=fun[var_]=exp RuleDelayed::rhs: Pattern var_ appears on the right-hand side of rule define[fun_Symbol,var_Symbol,exp_]:>(fun[var_]=exp). >> I complains a little, the definition has been recorded: In[2]:= ?define Global`define define[fun_Symbol,var_Symbol,exp_]:=fun[var_]=exp And it works: In[3]:= define[f,x,x^2] Out[3]= x^2 In[4]:= ?f Global`f f[x_]=x^2 If the function and variable name are not passed to define[], then it is not possible to remove the dependence on the x and g symbols, unless we establish a convention that the function being defined is always 'g' and the function variable is always 'x'. This might lead to trouble when 'x' has global values. So how do we write this 'define' function with this convention? We might naively try In[5]:= define2[exp_]:=g[x_]=exp But it won't quite work ... In[6]:= define2[x+x^2] Out[6]= x+x^2 In[7]:= ?g Global`g g[x$_]=x+x^2 What happens is that 'x' inside g[x_] gets automatically localized (renamed), and therefore it will no longer be the same as the global 'x' variable used in the expression being assigned to g[x_]. So how do we work around this problem? The simplest way is to use the previous define[] function, and In[9]:= define3[exp_]:=define[g,x,exp] In[10]:= define3[x+x^2] Out[10]= x+x^2 In[11]:= ?g Global`g g[x_]=x+x^2 I hope this help, Szabolcs Horv=E1t