Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
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_]

Mathematica graphics


FullForm[a - 2 b]

Mathematica graphics

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.

share|improve this answer

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
share|improve this answer
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.