0
|
4493 Views
|
4 Replies
|
3 Total Likes
View groups...
Share
GROUPS:

# Plus, Times, Power pattern matching treated differently than generic

Posted 10 years ago
 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:= FullForm[exp1 = a x y t^(4 z) + w t] Out//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:= FullForm[exp2= pl[ti[t,w],ti[a,pw[t,ti[4,z]],x,y]]] Out//FullForm= pl[ti[t,w],ti[a,pw[t,ti[4,z]],x,y]] (1) In:= Cases[exp1,Times[c__]:> {c},{3}] Out= {{t},{4 z}} (2) In:= Cases[exp1,c_Times :> {c},{3}] Out= {{4 z}}  But, (3) In:= Cases[exp2,ti[c__]:> {c},{3}] Out= {{4,z}} (4) In:= Cases[exp2,c_ti:> {c},{3}] Out= {{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?
4 Replies
Sort By:
Posted 10 years ago
 Thanks. The reference is very helpful.
Posted 10 years ago
 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 10 years ago
 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 10 years ago
 Times[c__] evaluates to just c__One could use In:= Cases[exp1, HoldPattern[Times[c__]] :> {c}, {3}] Out= {{4, z}}