Re: Re: Crossreference, code documentation
- To: mathgroup at christensen.cybernetics.net
- Subject: [mg1693] Re: [mg1619] Re: Crossreference, code documentation
- From: Richard Mercer <richard at seuss.math.wright.edu>
- Date: Mon, 17 Jul 1995 02:24:24 -0400
Dave Wagner writes:
> I have developed a function for the book that I'm writing
> that I think might help you. This function finds all
> symbols in an expression without allowing anything to
> evaluate:
>
> In[1]:=
> SetAttributes[FindSymbols, HoldFirst]
> FindSymbols[expr_] :=
> Switch[Head[Unevaluated[expr]],
> String | Integer | Real | Complex | Rational,
> {}, Symbol, {HoldForm[expr]}, _,
> Union[Flatten[ReleaseHold[
> Map[FindSymbols,
> Apply[List,
> Hold[expr], {1}],
> {2}] ]],
> FindSymbols @@ HeldPart[Hold[expr],
> 1, 0] ] ]
>
The following alternative seems to duplicate the behavior of FindSymbols.
Attributes[FindSymbols1] = {HoldFirst};
FindSymbols1[expr_]:=
Cases[Unevaluated[expr],s_Symbol:>HoldForm[s],Infinity,Heads->True] //Union;
(The Union at the end was his suggestion.)
This implementation is not surprisingly about 10 times faster since it uses an
internal command.
In Dave's defense, his code is a good example of recursive functional
programming, an important technique when dealing with Mathematica expressions.
There is not always a "miracle" solution like Cases available.
Also, neither is perfect as they both pull in unwanted heads, e.g.
In[12]:=
FindSymbols[h/(2*Pi) Sqrt[p^2 + m^2 c^4]/Gamma[z/2]]
Out[12]=
{c, Gamma, h, m, p, Pi, Plus, Power, Sqrt, Times, z}
One may not want the System symbols Gamma, Pi, Plus, Power, Sqrt and Times in
this list.
Richard Mercer