0
$\begingroup$

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.

$\endgroup$
  • 2
    $\begingroup$ Check their FullForms :) $\endgroup$ – rm -rf Jan 16 '14 at 6:13
  • $\begingroup$ Oh @rm-rf, just noticed your comment after posting answer; again... $\endgroup$ – carlosayam Jan 16 '14 at 6:59
3
$\begingroup$

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.

$\endgroup$
-1
$\begingroup$

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
$\endgroup$
  • $\begingroup$ 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 $\endgroup$ – carlosayam Jan 16 '14 at 23:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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