Get list of function variables?
- To: mathgroup at smc.vnet.net
- Subject: [mg83312] Get list of function variables?
- From: Thomas E Burton <tburton at brahea.com>
- Date: Sat, 17 Nov 2007 05:23:36 -0500 (EST)
Mathematica offers many ways to assign values to symbols, but if we
restrict attention to DownValues (look it up), then solutions are
indeed simple. First let's add a two more examples illustrating very
common definitions
f[w_Real, x_Integer, y_String, z_List] := "whatever"
(* overload f with a second set of arguments *)
g[3, 4] := "bingo!"
(* add a definition specific to particular values of arguments *)
Then one solution is
getVariables[f_] := Map[ReleaseHold, Apply[List, DownValues[f][[All,
1]], {2}]]
Parsing this from inside out, it says
(1) Grab the list of left members of DownValues of f.
(2) Reach inside the HoldPattern and replace f[args] with List[args].
(3) Release HoldPattern.
Note that arguments are generally patterns ("x_", "w_Real", etc.) but
can be specific symbols ("3","4"), and that this version of
getVariables retains this distinction. If you don't care to see this,
you can easily strip these off:
getVariables2[f_] := getVariables[f] /. p_Pattern :> First[p]
> 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}