RE: Condition vs PatternTest
- To: mathgroup at smc.vnet.net
- Subject: [mg42105] RE: [mg42081] Condition vs PatternTest
- From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
- Date: Thu, 19 Jun 2003 03:59:23 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
>-----Original Message----- >From: Ersek, Ted R [mailto:ErsekTR at navair.navy.mil] To: mathgroup at smc.vnet.net >Sent: Wednesday, June 18, 2003 8:11 AM >To: mathgroup at smc.vnet.net >Subject: [mg42105] [mg42081] Condition vs PatternTest > > >I wonder if people can help me understand the difference between >(pattn?test) and (pattn/;test). > >I understand when each form is normally used, but I want to >understand what >is happening under the hood. >Typical usage of (pattn?test) and (pattn/;test) are given in f1 and f2 >below. > >Clear[f1,f2] >f1[x_?Positive] := x+1 >f2[x_,y_]/;x<y := x+y > >However, we can define g1, g2 below which give the same result >as f1, f2 >respectively. Notice how the test in (g2) must carfully >prevent evaluation. > >Clear[g1,g2] >g1[x_/;Positive[x]]:=x+1 >g2[x_,y_]?(Function[a,Part[Unevaluated[a],1]<Part[Unevaluated[a >],2],{HoldAll >}]):=x+y > >Can somebody explain how evaluation of (pattn?test) differs >from evaluation >of (pattn/;test). > >----------- > Thanks, > Ted Ersek > Get Mathematica tips, tricks from > http://www.verbeia.com/mathematica/tips/Tricks.html > Ted, see e.g. In[1]:= $RecursionLimit = 20; In[2]:= g3[x_, y_, z_]?((c = {c, #}; True) &) := c In[3]:= c = {}; g3[1, 2, 3]; In[4]:= d = ReplaceRepeated[{} , {} -> {{}, {}}, MaxIterations -> 16]; In[5]:= d == c Out[5]= True In[6]:= f3[x_, y_, z_] /; (c = {c, f3[x, y, z]}; True) := c In[7]:= c = {}; f3[1, 2, 3]; In[8]:= d = ReplaceRepeated[{}, a_ :> {{}, a}, MaxIterations -> 8]; In[9]:= d == c Out[9]= True (I didn't copy the error messages, and I wouldn't consider application g2 be typically typical). This indicates, there are fine differences in evaluation. >From the semantics, the essential difference is that with patt ? test the (whole) matched pattern is submitted to test[patt], whereas with Condition[patt, test] matched pattern variables from pattern patt may be used within expression test. Also for definitions with Module, Block, or With local variables may be shared with test. The latter gives rise to the Trott-Strzebonski device for testing evaluated parts of an expression. Look that up in http://library.wolfram.com/infocenter , also the fine analyses Allan Hayes has written on this topic! http://forums.wolfram.com/mathgroup/archive -- Hartmut Wolf