Message Boards Message Boards

4 Replies
3 Total Likes
View groups...
Share this post:

Plus, Times, Power pattern matching treated differently than generic

I'm trying to understand how pattern matching occurs in Mathematica and seeing results different from my expectations. It does seem Times[] in particular, and likely Plus and Power have properties which are causing problems for me. In the examples below, I'm trying to understand the differences between matching on

Times[c__] and c_Times.

Here is an example:

In[11]:= FullForm[exp1 = a x y t^(4 z) + w t]
Out[11]//FullForm= Plus[Times[t,w],Times[a,Power[t,Times[4,z]],x,y]]

The "generic" version, replacing Plus with pl, Times with ti and Power with pw, I have

In[17]:= FullForm[exp2= pl[ti[t,w],ti[a,pw[t,ti[4,z]],x,y]]]
Out[17]//FullForm= pl[ti[t,w],ti[a,pw[t,ti[4,z]],x,y]]

In[15]:= Cases[exp1,Times[c__]:> {c},{3}]
Out[15]= {{t},{4 z}}

In[16]:= Cases[exp1,c_Times :> {c},{3}]
Out[16]= {{4 z}}


In[20]:= Cases[exp2,ti[c__]:> {c},{3}]
Out[20]= {{4,z}}

In[21]:= Cases[exp2,c_ti:> {c},{3}]
Out[21]= {{ti[4,z]}}

The TreeForm for exp1 and exp2 appear identical, so I expected the same pattern matching process to be identical also. That does not appear to be the case.

I understand the difference in the display of the results for expressions (2) and (4). It is the discrepancy between results for expressions (1) and (3) that has been stumped and concerned. In particular, results for expressions (2), (3), and (4) I expected. It is expression (1) that is problematic to me.

What is explanation?

POSTED BY: Lawrence Winkler
4 Replies

Thanks. The reference is very helpful.

POSTED BY: Lawrence Winkler

Isn't it natural that if Plus[x, y, z, ...] is x + y + z + ... , then the sum or the product of a single term x, like Plus[x] or Times[x] should evaluate to just x? Of course, x can be any expression, including something with patterns in it.

Plus and Times do have special attributes which are useful for pattern matching, see

POSTED BY: Ilian Gachevski

Thanks. Testing also shows that

Plus[c__] and Power[c__] evaluate to c__

Now I have to ask "Why?". What is the underlying rationale for Mathematica deciding on this interpretation? In creating my own functions, are there some reasons why I might want my functions to behave the same way? Are there attributes of these three functions which cause this interpretation?

POSTED BY: Lawrence Winkler
POSTED BY: Ilian Gachevski
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract