Re: Programming
- To: mathgroup at smc.vnet.net
- Subject: [mg2848] Re: Programming
- From: wagner at bullwinkle.cs.Colorado.EDU (Dave Wagner)
- Date: Wed, 27 Dec 1995 00:47:42 -0500
- Organization: University of Colorado, Boulder
In article <4bfr53$ld9 at dragonfly.wri.com>, Richard J Fateman <fateman at peoplesparc.cs.berkeley.edu> wrote: >In article <4bammu$cgv at dragonfly.wri.com>, >Robert Villegas <villegas at buka.wri.com> wrote: >>In article <4b8583$app at dragonfly.wri.com> Jack Goldberg <jackgold at umich.edu> >>writes: >.... >The difficulty faced here is not knowing in what order Mathematica >applies rules. It orders them in some way, but other than >trying to do the more specific before the more general, it >is not specified. > >If you have 2 rules Foo[expr_]:= .... try one thing > Foo[expr_]:= .... try something else, > >and do ??Foo > >it would be nice if the rule set displayed gave you a hint >as to how it was going to work, and also if you could rearrange >these rules. > > I think, however, you cannot. This is quite trivial to do. The rules for a symbol are stored in one of several places: DownValues[s], UpValues[s], etc., depending on what kind of rule that is. The kinds of rules in your examples are DownValues. There is nothing to prevent you from reordering them: Here are two rules for foo. (Local) In[2]:= foo[a_] := a+1 foo[a_^2] := a+1 The default order is for the more specific rule to be tried first. (Local) In[4]:= foo[x^2] (Local) Out[4]= 1 + x DownValues[foo] shows this order. (Local) In[5]:= DownValues[foo] (Local) Out[5]= 2 {Literal[foo[(a_) ]] :> a + 1, Literal[foo[a_]] :> a + 1} Reverse the order manually. (Local) In[6]:= DownValues[foo] = RotateLeft[DownValues[foo]] (Local) Out[6]= {Literal[foo[a_]] :> a + 1, 2 Literal[foo[(a_) ]] :> a + 1} Now the rule for foo[x_^2] is never seen; all calls to foo are trapped by the more general rule for foo[x_]. (Local) In[7]:= foo[a^2] (Local) Out[7]= 2 1 + a One thing that you can't do is change the order of DownValues relative to UpValues, for example. The latter are always tried before the former. See Wolfram's book for details. Dave Wagner Principia Consulting (303) 786-8371 dbwagner at princon.com http://www.princon.com/princon