# MatchQ returns False for a match for e1 ** e2 while matching both e1 and e2

I used a simple predicate realQ[x_] := MemberQ[{Real, Integer, Rational}, Head[x]]. With that predicate both MatchQ[2 e1, (k1_?realQ x_)] and MatchQ[(- 2 e2), (k2_?realQ y_)] returned True. But MatchQ[2 e1 ** (- 2 e2), (k1_?realQ x_) ** (k2_?realQ y_)] returned False. Any suggestion as to why that happened?

• Did you already look at the result of FullForm[2 e1 ** (-2 e2)] and compare it with the result of FullForm[(2 e1) ** (-2 e2)]? Commented Jun 9, 2022 at 14:36
• You were missing a _ for the x_ parameter in the definition of realQ; I assume that you actually had that in your notebook, or all your MatchQ expressions would return False without it. Commented Jun 9, 2022 at 14:45

Your seem to want your last expression interpreted as (2 e1) ** (-2 e2), i.e the NonCommutativeMultiply between (2 e1) and (2 e2).

However, regular multiplication (Times) has lower priority than NonCommutativeMultiply, so the expression as you wrote it actually interpreted as though it was grouped this way:

2 e1 ** (-2 e2) == 2 ( e1 ** (-2 e2) )


You can see that using FullForm:

FullForm[2 e1 ** (-2 e2)]

(* Out: Times[2, NonCommutativeMultiply[e1, Times[-2, e2]]] *)


To enforce your interpretation, you need to add an explicit set of parentheses:

(2 e1) ** (-2 e2)

FullForm[(2 e1) ** (-2 e2)]
(* Out: NonCommutativeMultiply[Times[2, e1], Times[-2, e2]] *)


The latter expression will match your pattern:

Clear[realQ]
realQ[x_] := MemberQ[{Real, Integer, Rational}, Head[x]]

MatchQ[2 e1, (k1_?realQ x_)]
(* Out: True *)

MatchQ[(-2 e2), (k2_?realQ y_)]
(* Out: True *)

MatchQ[(2 e1) ** (-2 e2), (k1_?realQ x_) ** (k2_?realQ y_)]
(* Out: True *)

• A hint that precedence is coming into play can be seen if you triple-click on the ** in the expression 2 e1 ** (-2 e2) in the frontend; you'll quickly see that what's being operated on by ** isn't what was expected. Commented Jun 9, 2022 at 16:45