Message Boards Message Boards

0
|
4693 Views
|
4 Replies
|
3 Total Likes
View groups...
Share
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]]


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

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

But,

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

(4)
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 http://reference.wolfram.com/language/tutorial/FlatAndOrderlessFunctions.html

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

Times[c__] evaluates to just c__

One could use

In[2]:= Cases[exp1, HoldPattern[Times[c__]] :> {c}, {3}]

Out[2]= {{4, z}}
POSTED BY: Ilian Gachevski
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract