Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2007

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

Search the Archive

Re: Get list of function variables?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg83425] Re: Get list of function variables?
  • From: Jason Quinn <jason.lee.quinn at gmail.com>
  • Date: Tue, 20 Nov 2007 03:49:53 -0500 (EST)
  • References: <fhjs5v$4t3$1@smc.vnet.net>

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.)

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.

Jason



  • Prev by Date: Re: data structures in Mathematica
  • Next by Date: Fast way of checking for perfect squares?
  • Previous by thread: Re: Get list of function variables?
  • Next by thread: Re: Get list of function variables?