Re: Get list of function variables?
- To: mathgroup at smc.vnet.net
- Subject: [mg83323] Re: Get list of function variables?
- From: Albert <awnl at arcor.net>
- Date: Sat, 17 Nov 2007 05:29:17 -0500 (EST)
- References: <fhjs5v$4t3$1@smc.vnet.net>
Jason Quinn wrote: > This seems simple but how do I get the arguments to an arbitrary > function? Ideally something like getVariables[f] that just accepts the > function name 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 for any suggestions, > Jason The trick is using DownValues, which contains all definitions made for a symbol that can be interpreted as function call. The following does roughly what you asked for: getVariables[f_] := First[Cases[ DownValues[f], f[args___] :> ({args} /. Verbatim[Pattern][x_, ___] :> x), Infinity ]] but for a real world case some more caution might be necessary: 1) there can be more than one definition for each function, e.g.: w[x_]:=1; w[k_,z_]:=2; you need to define what you want to get returned then (in the above code you could just remove the call to First to get a list of argument lists)... 2) if definitions for the symbols used as variable names have been made, the above code will fail and you will need to wrap the result in Hold or HoldForm in some way and be very careful when extracting the variables to prevent them from being evaluated. 3) Very often, the patterns of functions are much more complicated, e.g.: realworld[x_?NumericQ,y_?NumericQ/;y>0,opts___?OptionQ] it might be quite some effort to get this to work for every possible case, depending on what you want as a result... Of course, whether these are problems for what you are trying to achieve and how you can overcome them depends on the functions it needs to work for and on what you are trying to do with the result... hth, albert