2
$\begingroup$

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?

$\endgroup$
2
  • 1
    $\begingroup$ 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)]? $\endgroup$ Commented Jun 9, 2022 at 14:36
  • $\begingroup$ 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. $\endgroup$
    – MarcoB
    Commented Jun 9, 2022 at 14:45

1 Answer 1

3
$\begingroup$

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 *)
$\endgroup$
1
  • $\begingroup$ 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. $\endgroup$ Commented Jun 9, 2022 at 16:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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