MathGroup Archive 1998

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

Search the Archive

Flat riddle




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




  • Prev by Date: few easy questions
  • Next by Date: Re: Problem with ->
  • Prev by thread: Re: few easy questions
  • Next by thread: Re: Flat riddle