Re: Get list of function variables?

*To*: mathgroup at smc.vnet.net*Subject*: [mg83515] Re: Get list of function variables?*From*: Szabolcs <szhorvat at gmail.com>*Date*: Thu, 22 Nov 2007 04:40:16 -0500 (EST)*References*: <fhjs5v$4t3$1@smc.vnet.net> <fhu7j5$7b1$1@smc.vnet.net>

On Nov 20, 9:58 am, Jason Quinn <jason.lee.quinn at gmail.com> wrote: > On Nov 16, 5:42 am, Jason Quinn <jason.lee.qu... at gmail.com> wrote: > > > This seems simple but how do I get the arguments to an arbitraryfunction? Ideally something like getVariables[f] that just accepts thefunctionname as its argument. > > > If I have f[x_,y_]:=a*x^2+b*y^2, getVariables[f] should return {x,y} > > If I have g[n_,m_]:=a*n^2+b*m^2, getVariables[g] should return {n,m} > > If I have h[w_,x_,y_,z_]:=A*w*x*y*z+B, getVariables[h] should return > > {w,x,y,z} > > Thanks everybody for your responses and help. I made two complete > solutions out of the help that was offered. > > getVariables1[function_] := (Map[ReleaseHold, > Apply[List, DownValues[function][[All, 1]], {2}]] /. > p_Pattern :> First[p])[[1]] > > getVariables2[function_] := > Union[First /@ > Cases[DownValues[function], > HoldPattern[Verbatim[HoldPattern][function[z__]]] :> z, > Infinity]] > > Both do what I required of them. The bottom solution does not always > preserve the order of the variables in its output but it appears the > top one does. I wouldn't have ever figured these out because I had no > idea about DownValues (and still don't quite get it even after reading > the Mathematica book.) Jason, It seems that you were not convinced by the previous posts that the original question does not really make sense in Mathematica (because there are no "function variables", or "functions", only patterns and transformation rules, and the pattern names don't carry any information by themselves). So here is an example of a mathematical function, implemented in Mathematica, on which getVariables[] does not work: factorial[0] = 1 factorial[n_] := n factorial[n-1] May I ask what you intend to use getVariables[] for? > I'm going to try to tackle the inverse problem: making a function out > of a list of variables. Not sure yet, but I'm guessing UpValues might > have something to do with it. > UpValues are the transformation rules used in situations similar to the following: In[1]:= sym /: f[sym] = 1 Out[1]= 1 In[2]:= ?f Global`f In[3]:= ?sym Global`sym f[sym]^=1 In[4]:= UpValues[sym] Out[4]= {HoldPattern[f[sym]] :> 1} In[5]:= DownValues[f] Out[5]= {} In[6]:= f[sym] Out[6]= 1 Szabolcs