# Pattern matching

This is a very simple question I hope you can help me with. I am experimenting with pattern matching. I want to write a pattern for a difference between two symbols, a-b, that recognises cases like {a-2,a-2b,f[x]-g[x]} as special cases while rejecting cases like {a,a+b,a+2b,f[x]+g[x]}.

So I started experimenting

Now when I write

MatchQ[a + 2b, a_ + b_]


It returns True

When I write

MatchQ[a - 2b, a_ - b_]


It returns False, which surprises me given the first code snippet returns True.

I imagined my question could be solved by:

mypattern = a_ - _Integer. b_.


But that doesn't seem to work. Any pointers greatly appreciated.

-
Check their FullForms :) – R. M. Jan 16 '14 at 6:13
Oh @rm-rf, just noticed your comment after posting answer; again... – carlosayam Jan 16 '14 at 6:59

Use FullForm to find the reason!

FullForm[a_ - b_]


whereas,

FullForm[a - 2 b]


Note how -2 is absorbed into Plus. Mathematica does not have a built-in "-" and therefore translates that into something using Plus. One needs to be aware of this when dealing with patterns involving polynomials.

Lot more details in this introductory guide prepared by the community.

-

Thanks guys - very helpful. I solved the original question now:

mylist = {a - 2, a - 2 b, f[x] - g[x], a, a + b, a + 2 b, f[x] + g[x]}
mypattern = a_ + _. b_ /; b < 0
MatchQ[#, mypattern] & /@ mylist

-
Good! Note that as said in the guide "/" is also not a built-in. You may also want to explore commutativity and associativity, Orderless and Flat properties in Mathematica terms; and OneIdentity, which is Mathematica 's way to say that Plus[x] is just x, kind of saying that Plus has an identity element without mentioning it. See here – carlosayam Jan 16 '14 at 23:40