Flat riddle
- To: mathgroup@smc.vnet.net
- Subject: [mg11458] Flat riddle
- From: Ersek_Ted%PAX1A@mr.nawcad.navy.mil
- Date: Thu, 12 Mar 1998 01:34:12 -0500
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