MathGroup Archive 2000

[Date Index] [Thread Index] [Author Index]

Search the Archive

A function to evaluate only parts matching a pattern

  • To: mathgroup at smc.vnet.net
  • Subject: [mg25612] A function to evaluate only parts matching a pattern
  • From: "Ersek, Ted R" <ErsekTR at navair.navy.mil>
  • Date: Mon, 16 Oct 2000 03:04:37 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

The function below evaluates all parts of a held expression that match a
certain pattern. This is based on some code Robby Villegas of Wolfram
Research discussed at the 1999 Developer Conference. There Micheal Trott and
Adam Strzebonski of Wolfram Research are mentioned as the inventors of this
trick discussed by Robby Villegas.

In[1]:=
  EvaluatePattern[expr_,pattn_]:=
   expr/.Pattern[p,pattn] :> With[{eval =p}, eval /; True]


I made it into a function and added (Pattern[p,pattn]). The nice part 
is that there is no need to use Module[{p}, _] 

-----------
The next cell creates a held expression and evaluates all sub expressions
with the Head Plus but nothing else evaluates. In this example
Erf[Infinity]+5, 1+3, 5+4, Sqrt[36]-Sqrt[16] evaluate to 6, 4, 9, 2
respectively since they each have the head Plus.

In[2]:=
 
demo=HoldForm[(Erf[Infinity]+5)*Sin[Pi/(1+3)]*Sqrt[5+4]/(Sqrt[36]-Sqrt[16])]
;
  EvaluatePattern[demo,_Plus]

Out[3]=
  HoldForm[(6*Sin[Pi/4]*Sqrt[9])/2]


Isn't that slick!  Now this function doesn't work if any of the definitions
below are used. Why is the definition above the only one that works?


 EvaluatePattern[expr_,pattn_]:=
  expr/.Pattern[p,pattn]:>(p/;True)

 EvaluatePattern[expr_,pattn_]:=
  expr/.Pattern[p,pattn]:>With[{eval=p},eval]

 EvaluatePattern[expr_,pattn_]:=
  expr/.Pattern[p,pattn]->p


--------------------
Regards,
Ted Ersek

Down load Mathematica tips, tricks from 
http://www.verbeia.com/mathematica/tips/Tricks.html




  • Prev by Date: Serious bug in FunctionExpand
  • Next by Date: Re: Unusual speedup of Table
  • Previous by thread: Serious bug in FunctionExpand
  • Next by thread: Re: A function to evaluate only parts matching a pattern