MathGroup Archive 2014

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

Search the Archive

Re: Why does _+_==2_ (or, why is HoldPattern required

On Mon, Jan 20, 2014 at 03:59:45AM -0500, Alan wrote:
> I'm a relatively new user of Mathematica, and the following behavior seems odd to me:
> In[1]:= _ + _
> Out[1]= 2 _
> Use of `Plus` here is just to illustrate a more general "problem with `Blank`.  I had expected pattern objects to resist such evaluation. This is possibly related to the fact that I was surprised by the following:
> In[2]:= Blank[] == Blank[]
> Out[2]= True
> Since each Blank[] can match anything, I find this conceptually to be the wrong behavior.  As an example of a counter-intuitive result:
> In[3]:= MatchQ[a + b, _ + _]
> Out[3]= False
> I understand that I can deal with this problem by using HoldPattern.
> In[4]:= MatchQ[a + b, HoldPattern[_ + _]]
> Out[4]= True

It can be dealt with even more simply:

In[1]:= MatchQ[a + b, x_ + y_]

Out[1]= True

> So my question is not how to deal with the problem, but rather is a request for an explanation of why the current pattern evaluation behavior is desirable.

The magic of Blank[] comes not from itself but from the semantic meaning
pattern matching functions attribute to it.  Arithmetic/mathematical functions
tend to treat all symbolic expressions equally, so Blank[]+Blank[] -> 2Black[]
just as f[]+f[] -> 2f[].  Of course, special logic could be put in to handel
Blank[] especially, but would that gain us much more than simplifying a couple
of edge cases?  And would the performance hit be justified?  Note, also, that
you're slightly pushing the problem around, because making Blank[] special to
Plus would mean MatchQ[x+x, _+_] would return False. 

I wasn't around 25 years ago, but I imagine they decided that the bright-line
rule "all symbolic expressions are treated the same way" was deemed easier to
remember and certainly more efficient than adding various special cases.  It's
not the only possible decision, but I personally find it a reasonable one.

Itai Seggev
Mathematica Algorithms R&D

  • Prev by Date: Re: Default value in pattern matching
  • Next by Date: Re: BSplineSurface & BSplineFunction_Extracting Data
  • Previous by thread: Re: Why does _+_==2_ (or, why is HoldPattern required for
  • Next by thread: Re: Why does _+_==2_ (or, why is HoldPattern required