       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:=
ClearAll[fpv]

fpv[patt_] :=
Cases[patt,
p_Pattern :> HoldForm @@ HeldPart[p, 1],
{0, Infinity},
]

Here's an example:

In:=
f[x_] := x^2

In:=
DownValues[f]
Out=
2
{Literal[f[x_]] :> x }

In:=
fpv[DownValues[f]]
Out=
{x}

We're not done; fpv doesn't work correctly in the following case:

In:=
Clear[g]
g[x_] := x /. y_->y+1
fpv[DownValues[g]]
Out=
{x, y}

y should not appear in the result.  The solution is to target fpv to
the left side of the rule:

In:=
DownValues[g][[1,1]]
Out=
Literal[g[x_]]

In:=
fpv[%]
Out=
{x}

This idea leads to the following function:

In:=
argnames[f_] := fpv[#[]]& /@ DownValues[f]

Here, we add a second rule for g.

In:=
g[q[x_, z_]] := w[x] + t[z]
In:=

argnames returns the arguments in separate sublists.  You may Flatten
and Union if this isn't what you want.

argnames[g]
Out=
{{x, z}, {x}}

Note that the symbols are wrapped in HoldForm to prevent evaluation.

In:=
InputForm[%]
Out//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