I am trying to match an expression that will be a sum of more than one terms, with the last one being a product. For example, the objecta+b+x*y. I am using the FullForm of the expression, which is the form Plus[a,b,Times[x,y]]. After reviewing documentation, pattern Plus[__,Times[_]] seems to be what I am looking for, and it gives correct result:

enter image description here

However, when I apply FullForm to the expression before trying the match, the pattern fails.

enter image description here

¿Why does this happen? I thought that the FullForm evaluation was performed beforehand.

  • 2
    $\begingroup$ Take a look at FullForm[Plus[a, b, Times[x, y]]] // FullForm. So you have to modify the pattern. e.g. MatchQ[FullForm[Plus[a, b, Times[x, y]]], _[Plus[__, Times[_]]]] $\endgroup$ Jul 18 at 18:14
  • $\begingroup$ Your have more problems beyond the misuse of FullForm. See my answer below for details $\endgroup$
    – m_goldberg
    Jul 18 at 20:11

Beside following the good advice Rohit Namjoshi has given in a comment, you need to become aware that pattern matching against Plusand Times is tricky because these operators have attributes (special rules) that cause strange things to happen when the patterns containing them are evaluated.

Consider the following:

You don't want

MatchQ[Plus[a, b, foo[x, y]], Plus[__, Times[_]]]

to return True but it does. The reason for this is that

Plus[__, Times[_]] // FullForm 


    Plus[Blank[], BlankSequence[]]

which will match any Plus expression with two or moore arguaments. What you want is something like

MatchQ[Plus[a, b, Times[x, y]], Plus[__, Times[__]]]

but that doesn't work either because

Plus[__, Times[__]] // FullForm


    Times[2, BlankSequence[]]

So what to do? I recommend using Inactivate.

Inactivate[MatchQ[a + b + x*y, Plus[__, Times[__]]], Plus | Times]
(* True *)

Inactivate[MatchQ[a + a + x*x, Plus[__, Times[__]]], Plus | Times]
(* True *)

Inactivate[MatchQ[a + b + foo[x, y], Plus[__, Times[__]]], Plus | Times]
(* False *)


On second thought perhaps using HoldPattern is better.

MatchQ[a + b + x*y, HoldPattern[Plus[__, Times[__]]]]
(* True *)

MatchQ[a + a + x*x, HoldPattern[Plus[__, Times[__]]]]
(* True *)

MatchQ[a + b + foo[x, y], HoldPattern[Plus[__, Times[__]]]]
(* False *)

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.