       Re: Get list of function variables?

• To: mathgroup at smc.vnet.net
• Subject: [mg83476] Re: Get list of function variables?
• From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
• Date: Wed, 21 Nov 2007 02:54:34 -0500 (EST)
• Organization: The Open University, Milton Keynes, UK
• References: <fhjs5v\$4t3\$1@smc.vnet.net> <fhu7j5\$7b1\$1@smc.vnet.net>

```Jason Quinn 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])[]
>
> 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.)

<snip>

Just an additional thought. Beware that, as written, both functions may
quickly fail to bring meaningful information, even with some simple
cases (or, to play on the safe side, you must get rid of most of the
most interesting features of the Mathematica programming language when
defining functions).

In:= getVariables1[
function_] := (Map[ReleaseHold,
Apply[List, DownValues[function][[All, 1]], {2}]] /.
p_Pattern :> First[p])[]

getVariables2[function_] :=
Union[First /@
Cases[DownValues[function],
HoldPattern[Verbatim[HoldPattern][function[z__]]] :> z,
Infinity]]

In:= f[___] := False
f = True;
f[_List] = "Lists are not allowed!";
g[x_, y_] := a*x^2 + b*y^2
g[p_Integer, q_Integer] := Mod[p, q]
g[m_?MatrixQ, v_?VectorQ] := m.v

In:= getVariables1 /@ {f, g}

Out= {{2}, {p, q}}

In:= getVariables2 /@ {f, g}

During evaluation of In:= First::normal: Nonatomic expression \
expected at position 1 in First. >>

During evaluation of In:= First::first: ___ has a length of zero \
and no first element. >>

Out= {{List, First, First[___]}, {p, q, x, y, m_, v_}}

Regards,
--
Jean-Marc

```

• Prev by Date: Re: Variable-length list?
• Next by Date: Re: Symbolic vector handling
• Previous by thread: Re: Get list of function variables?
• Next by thread: Re: Get list of function variables?