MathGroup Archive 2007

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Get list of function variables?

  • To: mathgroup at
  • Subject: [mg83323] Re: Get list of function variables?
  • From: Albert <awnl at>
  • Date: Sat, 17 Nov 2007 05:29:17 -0500 (EST)
  • References: <fhjs5v$4t3$>

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[
    f[args___] :> ({args} /. Verbatim[Pattern][x_, ___] :> x),

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.:
    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,
    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...



  • Prev by Date: Re: Piecewise inside a Module or Block, I don't understand this behavior.
  • Next by Date: Re: Re: Re: Mac OS X 10.5 - Mathematica 5.1 hangs - 6.0 works?
  • Previous by thread: Re: Get list of function variables?
  • Next by thread: Re: Get list of function variables?