Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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
2  
Check their FullForms :) –  rm -rf Jan 16 at 6:13
    
Oh @rm-rf, just noticed your comment after posting answer; again... –  caya Jan 16 at 6:59
add comment

2 Answers

Use FullForm to find the reason!

FullForm[a_ - b_]

Mathematica graphics

whereas,

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
add comment

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 –  caya Jan 16 at 23:40
add comment

Your Answer

 
discard

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.