Re: Flat riddle
- To: mathgroup@smc.vnet.net
- Subject: [mg11497] Re: [mg11458] Flat riddle
- From: "C. Woll" <carlw@u.washington.edu>
- Date: Fri, 13 Mar 1998 12:21:44 -0500
Hi Ted, Here is an attempted solution, which may do what you want. ClearAll[f] SetAttributes[f,{Flat,OneIdentity}] a_f /; Length[Unevaluated[a]]==1 := Identity@@Unevaluated[a] It worked on the examples you gave below. The idea is that the rule a_f ... only fires after Flat has done its thing. The problem is that defining a rule this way requires you to use Unevaluated so that you don't get into an infinite loop. Is this what you were looking for? Carl Woll Dept of Physics U of Washington On Thu, 12 Mar 1998 Ersek_Ted%PAX1A@mr.nawcad.navy.mil wrote: > > At http://www.wolfram.com/support/Kernel/Symbols/findsymbol.cgi > Wolfram Research Technical Support points out that you will run into > trouble if you have a function (f) with the Flat attribute, and the > rule ( f[p_]:=p ). > If (f) has these properties then ( f[1,2] ) will result in infinite > iteration. > > However: > (1) Plus is flat. > (2) ClearAll[p]; Plus[p] evaluates to (p). (3) ClearAll[a,b]; > Plus[a,b] doesn't result in infinite iteration. The same thing goes for > Times. So how can a user create a function that works this way? > What works for Plus and Times should be possible for a user defined > function! > > One Mathematica expert has told me it's impossible. I couldn't believe > it, so I continued searching for a solution. I think I found one. > > In[1]:= > $Post=ReplaceAll[#,f[a_]->a]&; > Attributes[f]={Flat,OneIdentity}; > > With the definitions above layers of (f) are automatically flattened in > Out[2]. > The Flat attribute is used in pattern matching to give Out[3]. In Out[4] > we see ( f[t] ) evaluates to (t). It seems to work. > > In[2]:= > f[1,2,f[3,4],f[5,f[6]]] > Out[2]= > f[1,2,3,4,5,6] > > In[3]:= > f[1,2,3]/.f[p_,q_]:>{p,q}/;Length[p]==2 > > Out[3]= > {f[1,2],3} > > In[4]:= > f[t] > > Out[4]= > t > > > Question: > Is it possible to do this without giving $Post a rule that must be > applied to every expression? > I was able to do this in the line below, but I have to add the rule at > the end of any Cell where it should be used. Is it possible to > automatically get this result without having the rule applied to every > expression? > > In[5]:= > Attributes[g]={Flat,OneIdentity}; > > In[6]:= > g[t]/.g[a_]->a > > Out[6]= > t > > > Ted Ersek > > >