[Date Index]
[Thread Index]
[Author Index]
Re: argument names
*To*: mathgroup at smc.vnet.net
*Subject*: [mg3720] Re: argument names
*From*: wagner at bullwinkle.cs.Colorado.EDU (Dave Wagner)
*Date*: Wed, 10 Apr 1996 02:13:39 -0400
*Organization*: University of Colorado, Boulder
*Sender*: owner-wri-mathgroup at wolfram.com
In article <4kd3e8$93v at dragonfly.wolfram.com>,
Andrew Watson <beau at vision.arc.nasa.gov> wrote:
>Is there a simple way to get the names of the arguments
>within a user-defined function? For example, given:
>
>f[x_] := x^2
>
>I would like a function g such that
>
>g[f] returns x, either as a symbol or a string.
First, here is a function called fpv that finds all pattern variables
in a pattern, and returns a list of them, individually wrapped in
HoldForm to prevent evaluation:
In[1]:=
ClearAll[fpv]
fpv[patt_] :=
Cases[patt,
p_Pattern :> HoldForm @@ HeldPart[p, 1],
{0, Infinity},
Heads->True
]
Here's an example:
In[3]:=
f[x_] := x^2
In[4]:=
DownValues[f]
Out[4]=
2
{Literal[f[x_]] :> x }
In[5]:=
fpv[DownValues[f]]
Out[5]=
{x}
We're not done; fpv doesn't work correctly in the following case:
In[6]:=
Clear[g]
g[x_] := x /. y_->y+1
fpv[DownValues[g]]
Out[8]=
{x, y}
y should not appear in the result. The solution is to target fpv to
the left side of the rule:
In[9]:=
DownValues[g][[1,1]]
Out[9]=
Literal[g[x_]]
In[10]:=
fpv[%]
Out[10]=
{x}
This idea leads to the following function:
In[11]:=
argnames[f_] := fpv[#[[1]]]& /@ DownValues[f]
Here, we add a second rule for g.
In[12]:=
g[q[x_, z_]] := w[x] + t[z]
In[13]:=
argnames returns the arguments in separate sublists. You may Flatten
and Union if this isn't what you want.
argnames[g]
Out[13]=
{{x, z}, {x}}
Note that the symbols are wrapped in HoldForm to prevent evaluation.
In[14]:=
InputForm[%]
Out[14]//InputForm=
{{HoldForm[x], HoldForm[z]}, {HoldForm[x]}}
You may also be interested in my article in TMJ 6(1) about "Dependency
Analysis" (from which the fpv function was taken), where I present a
package that does the exact opposite of what you are asking -- it finds
all the symbols in the definition of a symbol that are *not*
arguments. The package correctly analyzes pure functions, modules, etc.
(i.e., any Mathematica construct that can introduce temporary symbols,
not just function definition). The intent of the package is to ease
the maintenance of large Mathematica programs.
Dave Wagner
Principia Consulting
(303) 786-8371
dbwagner at princon.com
http://www.princon.com/princon
==== [MESSAGE SEPARATOR] ====
Prev by Date:
**Combining 2D With Different Scales**
Next by Date:
**Re: ReadList Expression: (Q)**
Previous by thread:
**argument names**
Next by thread:
**Re: {mg3701] Re: Problem with Diff. Equation**
| |